Javascript 当Algo正确时,元素交换不正确
我想我有一个关于泡泡运动交换的基本问题。我正在尝试构建一个排序可视化工具,需要在bubblesort中交换2个数组元素时交换它们的高度。我已经验证了algo与包含正确元素的动画数组一起工作。我的问题是,当我调整阵列条的高度时,无法获得正确的交换。 这是我的沙箱: 编辑:如果你不想点击链接,这里有一些代码: BubbleSort.js:Javascript 当Algo正确时,元素交换不正确,javascript,reactjs,Javascript,Reactjs,我想我有一个关于泡泡运动交换的基本问题。我正在尝试构建一个排序可视化工具,需要在bubblesort中交换2个数组元素时交换它们的高度。我已经验证了algo与包含正确元素的动画数组一起工作。我的问题是,当我调整阵列条的高度时,无法获得正确的交换。 这是我的沙箱: 编辑:如果你不想点击链接,这里有一些代码: BubbleSort.js: const animations = []; export const swap = (arr, current, next) => { anim
const animations = [];
export const swap = (arr, current, next) => {
animations.push(arr[current]);
animations.push(arr[next]);
let curVal = arr[current];
arr[current] = arr[next];
arr[next] = curVal;
getAnimations(animations);
}
export const getAnimations = (animations) => {
const newAnims = animations;
return newAnims;
}
export const doBubbleSort = (array) => {
//start the endIndex at the last index of the arrayay
let newArray = array;
let endIndex = newArray.length - 1;
//run the loop until the endIndex(sorted portion) is the 0 (the full newArrayay)
while(endIndex > 0){
// count the number of swaps to short circuit the loop if it is already sorted
let swaps = 0;
//reset the currentIndex to the beginning of the newArrayay each time a new element is sorted
let currentIndex = 0;
// loop over the newArrayay, comparing each pair of elements until the comparison element reaches the sorted portion of the newArrayay
while(currentIndex < endIndex){
// uncomment this line to see the comparison in action
//console.log(newArray[currentIndex], newArray[currentIndex + 1])
// if the current element is greater than the element in front of it
if(newArray[currentIndex] > newArray[currentIndex + 1]){
//swap the 2 elements using our helper function
swap(newArray, currentIndex, currentIndex + 1);
// add 1 to the swaps counter
swaps++;
}
//increase the currentIndex to continue iterating through the newArrayay
currentIndex++;
}
//stop the loop if there were no swaps because the newArrayay must be already sorted
if(swaps === 0)break;
// subtract the endIndex number to account for the new element added to the newArrayay
endIndex--;
}
return newArray;
}
export default animations;
const动画=[];
导出常量交换=(arr、当前、下一个)=>{
动画.push(arr[current]);
动画.push(arr[next]);
设curVal=arr[电流];
arr[current]=arr[next];
arr[next]=曲线;
获取动画(动画);
}
导出常量getAnimations=(动画)=>{
const newAnims=动画;
返回新动画;
}
导出常量DoubbleSort=(数组)=>{
//在数组的最后一个索引处开始endIndex
设newArray=array;
让endIndex=newArray.length-1;
//运行循环,直到endIndex(排序部分)为0(完整的newArrayay)
而(endIndex>0){
//如果回路已排序,则计算使其短路的交换次数
设互换=0;
//每次对新元素排序时,将currentIndex重置为newArrayay的开头
设currentIndex=0;
//循环newArrayay,比较每对元素,直到比较元素到达newArrayay的排序部分
while(currentIndexnewArray[currentIndex+1]){
//使用我们的helper函数交换这两个元素
交换(newArray、currentIndex、currentIndex+1);
//向掉期计数器添加1
交换++;
}
//增加currentIndex以继续遍历newArrayay
currentIndex++;
}
//如果没有交换,则停止循环,因为newArrayay必须已排序
如果(互换===0)中断;
//减去endIndex编号以说明添加到newArrayay的新元素
endIndex--;
}
返回新数组;
}
导出默认动画;
这是算法。在这里,我尝试交换要在sceen上显示的元素:
bubbleSort(){
let anims = [];
const sortedArray = doBubbleSort(this.state.array);
let bars = [];
//Only initial positions
//console.log(arrayBars); //inital log
anims = animations;
//console.log(anims);
for(let i = 0; i < anims.length; i+=2){
let swap = 0;
let firstBar = anims[i] + 'px';
let secondBar = anims[i+1] + 'px';
bars = document.getElementsByClassName('array-bar');
console.log('anim: ' + firstBar + ' ' + secondBar);
//console.log(currentArrayBars);
setTimeout(() => {
let firstIdx = 0;
let secondIdx = 0;
while(swap == 0)
{
for(let j = 0; j < bars.length; j++){
if(bars[j].style.height == firstBar){
firstIdx = j;
bars[j].style.backGroundColor = 'red';
}
else if(bars[j].style.height == secondBar){
secondIdx = j;
bars[j].style.backGroundColor = 'red';
}
}
let temp = bars[firstIdx].style.height;
bars[firstIdx].style.height = bars[secondIdx].style.height;
bars[secondIdx].style.height = temp;
swap++;
}
}, i * 1)
}
anims.length = 0;
};
render(){
const {array} = this.state;
return (
<div className = "array-container">
{array.map((value, idx) => (
<div className = "array-bar" key = {idx}
style = {{height: `${value}px`}}>
</div>
))}
<button onClick ={() => this.resetArray()}> Generate New Array </button>
<button onClick ={() => this.bubbleSort()}> Bubble Sort</button>
</div>
);
}
}
export default SortingVisualizer
function randomIntFromIntervals(min, max){
return Math.floor(Math.random() * (max - min + 1) + min)
}
bubbleSort(){
让动画=[];
const sortedArray=dobblesort(this.state.array);
设条=[];
//仅初始位置
//console.log(arrayBars);//初始日志
动画=动画;
//console.log(anims);
for(设i=0;i{
设firstIdx=0;
设secondIdx=0;
while(swap==0)
{
对于(设j=0;j(
))}
this.resetArray()}>生成新数组
this.bubbleSort()}>Bubble排序
);
}
}
导出默认排序可视化工具
函数RandomIntFromInterval(最小值、最大值){
返回Math.floor(Math.random()*(max-min+1)+min)
}
编辑:我相信我可能已经解决了。我将尝试使用一个随机数组填充唯一的VAL no DUP并在问题中包含代码的有趣部分。我们不必离开StackOverflow来获得有关代码的基本含义。@Marc添加了新代码您应该为每个元素使用唯一的键,否则react无法修补Dom。现在您正在使用数组索引。元素的位置会随着您的排序而变化,但是如果没有稳定的键,您将无法很好地检测到变化,您将看到这些奇怪的东西。我建议您在每个元素上添加一个Id字段。@Brenden是的,这是我的问题。我最终只是让数组创建unqiue元素,而不是复制来解决它,但这将是一种(可能更好)解决方法。