在React中为Quicksort可视化器制作动画

问题描述

我正在尝试为quicksort可视化器制作动画,以更好地理解算法。我已经写了一个有效的算法,但是我对动画有点困惑。我遵循了mergesort的教程,该教程将所有要比较的值推入数组中,并且做了类似的事情。目前,我的代码为正在比较的值着色,但不会重新排列值的顺序。我不确定如何将它们交换为正确的顺序。任何帮助或指导将不胜感激!

这是Javascript中的算法:


    export function getQuickSortAnimations(array) {
      const animations = [];
      if (array.length <= 1) {
        return array;
      }
      

      const pivot = array[array.length-1];
      const leftArr = [];
      const rightArr = [];
      for (const el of array.slice(0,array.length-1)){
        el <= pivot ? leftArr.push(el) : rightArr.push(el);
        animations.push(["comparison1",el,pivot]); //To colour the compared values
        animations.push(["comparison2",pivot]); //To take the colours off
     
    }


      let sortArray= [...getQuickSortAnimations(leftArr),pivot,...getQuickSortAnimations(rightArr)];

      return [animations,sortArray];

    }

这是React中的动画位:

quickSort() {
        const [animations,array] = getQuickSortAnimations(this.state.array);
        for (let i = 0; i < animations.length; i++) {
            const isColorChange = animations[i][0] === "comparison1" || animations[i][0] === "comparison2";
            const arrayBars = document.getElementsByClassName('array-bar');
            if(isColorChange === true) {
                const [comparison,barOneIndex,barTwoIndex] = animations[i];
                const color = (animations[i][0] === "comparison1") ? 'navy' : 'pink';
                const barOneStyle = arrayBars[barOneIndex]?arrayBars[barOneIndex].style: {};
                const barTwoStyle = arrayBars[barTwoIndex]?arrayBars[barTwoIndex].style:{};
                setTimeout(() => {
                    barOneStyle.backgroundColor = color;
                    barTwoStyle.backgroundColor = color;
                },i * ANIMATION_SPEED_MS);
            } 
            else { //This is the section that I am not sure about
                const [swap,barIndex,newHeight] = animations[i]; 
                if (barIndex === -1) {
                    continue;
                }
                const barStyle = arrayBars[barIndex]?arrayBars[barIndex].style:{};
                setTimeout(() => {
                    barStyle.height = `${newHeight}px`;
                },i * ANIMATION_SPEED_MS);  
            }        
        } 
        }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...