我很难可视化排序算法

发布于 2025-02-10 04:35:25 字数 2088 浏览 2 评论 0原文

我正在尝试与React可视化排序算法,我的算法工作正常,但我想将其链接到Divs上的Divs,因为分类算法对给定的数组进行了变化,我只能在最后阶段工作,例如,DOM上的Divs从未排序的数组中拿出高度,当我单击“排序”按钮时,而不是随着算法对未分类数组的排序,而不是动态更改其高度时,他们只是等待删除算法完成排序,然后在一个实例中等待Div从未分类的高度转到排序的高度(我试图做SetteMeTOut,但它对我的预期从未有效,它只是进行一次超时而不是在每次迭代中进行)。 这是我的代码:

function App() {
  const [array, setArray] = useState();
  const elements = useRef();
  const test = (Array) => { 
      if(Array){
        for(let i=0; i < Array.length; i++){
          elements.current.children[i].style.height = `${Array[i]*2}vh`;
        }
      } 
  };
  useEffect(()=> {
    const startArray = [];
    for(let i=0; i < 51; i++){
      let randomNumber = Math.floor(Math.random() * 27);
      if(randomNumber !== 0){
        startArray.push(randomNumber)
      }
    }
    setArray(startArray)
  }, [])
  const bubbleSort = arraY => {
    let iteration = true;
    let shouldContinue = false;
    let count = arraY.length-1;
    while(iteration){
        shouldContinue = false
        if(count > 0){
            for(let i=0; i < count; i++){
              shouldContinue = true;
                if(arraY[i] > arraY[i+1]){
                  let smaller = arraY[i+1];
                  arraY[i+1] = arraY[i];
                  arraY[i] = smaller;
                  test(arraY);
                  }
                }
        }
            count = count -1

            if(!shouldContinue){
                iteration = false
            }
    }
    return array
  }
  const sort = ()=> {
    bubbleSort(array);
  }

  return (
    <div className="App">
      <nav>
        <h1 onClick={sort}>BUBBLE SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
      </nav>
      <div className='container' ref={elements}>
        {array && array.map(item=>{
          return <div style={{height: `${item*2}vh`}}></div>
        })
        }
      </div>
    </div>
  );
}

任何帮助都将受到赞赏

I am trying to visualize a sorting algorithm with react, my algorithm works fine but i want to link it to divs on the DOM that change their height as the sorting algorithms sorts a given array, i have only made it work at the last stage, for example divs on the DOM take their height from an unsorted array and when i click on the sort button, instead of dynamicly changing their height as the algorithm sorts the unsorted array, they just wait untill the algorithm finishes sorting and then in one instance the div go from unsorted height to sorted height (i have tried to do setTimeout but it never worked for me as it intended, it just does one timeout instead of doing it in every iteration).
This is my code:

function App() {
  const [array, setArray] = useState();
  const elements = useRef();
  const test = (Array) => { 
      if(Array){
        for(let i=0; i < Array.length; i++){
          elements.current.children[i].style.height = `${Array[i]*2}vh`;
        }
      } 
  };
  useEffect(()=> {
    const startArray = [];
    for(let i=0; i < 51; i++){
      let randomNumber = Math.floor(Math.random() * 27);
      if(randomNumber !== 0){
        startArray.push(randomNumber)
      }
    }
    setArray(startArray)
  }, [])
  const bubbleSort = arraY => {
    let iteration = true;
    let shouldContinue = false;
    let count = arraY.length-1;
    while(iteration){
        shouldContinue = false
        if(count > 0){
            for(let i=0; i < count; i++){
              shouldContinue = true;
                if(arraY[i] > arraY[i+1]){
                  let smaller = arraY[i+1];
                  arraY[i+1] = arraY[i];
                  arraY[i] = smaller;
                  test(arraY);
                  }
                }
        }
            count = count -1

            if(!shouldContinue){
                iteration = false
            }
    }
    return array
  }
  const sort = ()=> {
    bubbleSort(array);
  }

  return (
    <div className="App">
      <nav>
        <h1 onClick={sort}>BUBBLE SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
        <h1 onClick={sort}>--- SORT</h1>
      </nav>
      <div className='container' ref={elements}>
        {array && array.map(item=>{
          return <div style={{height: `${item*2}vh`}}></div>
        })
        }
      </div>
    </div>
  );
}

Any help is appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聊慰 2025-02-17 04:35:25

您需要执行一种操作,然后设置状态,以便对重新呈现。您还需要设置一些超时,以避免一切都如此迅速地发生,您什么都看不到任何东西。类似的事情:

const [currentlyAt, setCurrentlyAt] = useState(0);

const bubbleSort () => {

   const newArray = [...]
   // perform one step of bubble sort, storing my position in the sort
   // with setCurrentlyAt, so I can resume it next time I'm called
   
   setArray(newArray);
   setTimeout(() => bubbleSort(), 500);  
}

这允许执行一个步骤(单个项目交换),状态更新,以便它将恢复,并且超时会为用户提供时间在恢复泡泡排序之前被用户看到并进行操作。下一个交换。

另外,请不要使用arrayarray作为变量名称,以避免阴影array,使用部分索要或至少arr。而且,您无需useref,您的逻辑是您在数组上映射的逻辑,并且基于数组值的div高度可以正常工作,您不想使用Ref手动编辑样式。

You need to do one sort operation, and then set the state, so that react re-renders. You also will need to set some timeout, to avoid it all happening so quickly you can't see anything. Something like this:

const [currentlyAt, setCurrentlyAt] = useState(0);

const bubbleSort () => {

   const newArray = [...]
   // perform one step of bubble sort, storing my position in the sort
   // with setCurrentlyAt, so I can resume it next time I'm called
   
   setArray(newArray);
   setTimeout(() => bubbleSort(), 500);  
}

This allows one step (a single item swap in bubble array) to be performed, state updates so it'll rerender, and timeout gives time for the rerender to be seen by the user before resuming the bubble sort and doing the next swap.

Also, please, don't use arraY and Array as variable names to avoid shadowing array, use something like partiallySorted or at least arr. And you don't need to useRef at all, your logic where you map over array and have div heights based on array value works fine, you don't want to manually edit the style using a ref.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文