简体   繁体   English

切换索引后数组未更新

[英]Array not being updated after switching indexs

I'm working on a visualizer for sorting algorithms.我正在开发用于排序算法的可视化工具。 Everything is working as intended until I got to the Selection Sort.在我进入选择排序之前,一切都按预期工作。 I understand that the Selection sort will make a pass and search for the MINIMUM value and then swap that the index that it started at in the array.我知道选择排序将通过并搜索 MINIMUM 值,然后交换它在数组中开始的索引。 However, each time it makes a pass, the i value doesn't change.但是,每次通过时, i值都不会改变。 I tested it by changing the color of the block the i index represents in my loop and it never changes, so the MINIMUM value just keeps switching to where ever the i is.我通过更改我的循环中i索引表示的块的颜色来测试它,它永远不会改变,所以 MINIMUM 值只是不断切换到i所在的位置。 You can view my project here on GitHub Pages, just use the left Navbar to choose Selection Sort and you can see the problem I'm having.您可以在 GitHub 页面上查看我的项目,只需使用左侧导航栏选择选择排序,您就可以看到我遇到的问题。 The bottom snippet is my swap function, it didn't do this with any of the other sort methods, only the selection sort.底部片段是我的swap function,它没有使用任何其他排序方法执行此操作,只有选择排序。

Github Pages -- https://kevin6767.github.io/sorting-algorithm-visualization/ Github Pages -- https://kevin6767.github.io/sorting-algorithm-visualization/

Selection function选择function

async function selectionSort() {
    let blocks = document.querySelectorAll('.block');

    for (let i = 0; i < blocks.length; i++) {
        // Assume a minimum value
        let min = i;
        for (let j = i + 1; j < blocks.length; j++) {
            blocks[j].style.backgroundColor = '#FF4949';
            blocks[min].style.backgroundColor = '#13CE66';
            blocks[i].style.backgroundColor = 'orange';

            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, frame_speed)
            );
            const value1 = Number(blocks[j].childNodes[0].innerHTML);
            const value2 = Number(blocks[min].childNodes[0].innerHTML);
            if (value1 < value2) {
                blocks[min].style.backgroundColor = '#58B7FF';
                min = j;
            }
            blocks[j].style.backgroundColor = '#58B7FF';
        }
        if (min !== i) {
            let tmp = blocks[i];
            blocks[i] = blocks[min];
            blocks[min] = tmp;
            await swap(blocks[i], blocks[min]);
            blocks = document.querySelectorAll('.block');
        }
        // Swap if new minimun value found
        blocks[i].style.backgroundColor = '#58B7FF';
    }
}

Swap function交换 function

function swap(el1, el2) {
    return new Promise((resolve) => {
        const style1 = window.getComputedStyle(el1);
        const style2 = window.getComputedStyle(el2);

        const transform1 = style1.getPropertyValue('transform');
        const transform2 = style2.getPropertyValue('transform');

        el1.style.transform = transform2;
        el2.style.transform = transform1;

        // Wait for the transition to end!
        window.requestAnimationFrame(function () {
            setTimeout(() => {
                container.insertBefore(el2, el1);
                resolve();
            }, 300);
        });
    });
}

I ended up fixing it.我最终修复了它。 It seems that I had to take the Nodelist array I was getting from just.querySelectorAll and convert that into an array using.Arrayfrom() which was pretty simple after some googling.看来我必须从 just.querySelectorAll 获取 Nodelist 数组,然后使用 .Arrayfrom() 将其转换为数组,这在谷歌搜索后非常简单。 From then on I needed to figure out how to update the array each pass, which once again was as simple as just moving one index from another.从那时起,我需要弄清楚如何在每次传递时更新数组,这又一次像从另一个索引移动一个索引一样简单。

The interesting part of the answer was how I was going to update the Nodelist itself that way all my css code would still work (This is a sorting visualizer, so it would show you what element it was on and highlight it with a color).答案中有趣的部分是我将如何更新节点列表本身,这样我的所有 css 代码仍然可以工作(这是一个排序可视化工具,因此它会显示它所在的元素并用颜色突出显示它)。 The answer however was right in front of me.然而,答案就在我面前。 Even though I turned the Nodelist array into a regular array, I was still able to apply styles to it.即使我将 Nodelist 数组变成了一个常规数组,我仍然能够将 styles 应用于它。 This meant I didn't have to mutate the Nodelist array at all and was just able to keep a seperate array within the function to work with.这意味着我根本不必改变 Nodelist 数组,只需在 function 中保留一个单独的数组即可使用。

PS. PS。 The algorithm did have a lot of trouble in the above snippet because I was comparing 2 strings in the if statement (value1 and value2) this is what caused a lot of the actual algorithm erroring and was simply fixed by adding a Number() function around my innerhtml code.该算法在上面的代码片段中确实存在很多问题,因为我在 if 语句(value1 和 value2)中比较了 2 个字符串,这是导致很多实际算法错误的原因,只需在周围添加 Number() function 即可解决我的innerhtml代码。

Selection选择

async function selectionSort() {
    let blocks = document.querySelectorAll('.block');
    let convertedBlocks = Array.from(blocks);
    let len = convertedBlocks.length;
    for (let i = 0; i < len; i++) {
        let min = i;
        for (let j = i + 1; j < len; j++) {
            convertedBlocks[j].style.backgroundColor = 'red';
            convertedBlocks[min].style.backgroundColor = 'green';
            convertedBlocks[i].style.backgroundColor = 'orange';
            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, frame_speed)
            );
            if (
                Number(convertedBlocks[min].childNodes[0].innerHTML) >
                Number(convertedBlocks[j].childNodes[0].innerHTML)
            ) {
                convertedBlocks[min].style.backgroundColor = '#58B7FF';
                min = j;
            }
            convertedBlocks[j].style.backgroundColor = '#58B7FF';
        }
        if (min !== i) {
            let tmp = convertedBlocks[i];
            convertedBlocks[i] = convertedBlocks[min];
            convertedBlocks[min] = tmp;
            await swap(convertedBlocks[i], convertedBlocks[min]);
        }
        convertedBlocks[min].style.backgroundColor = '#58B7FF';
        convertedBlocks[i].style.backgroundColor = '#58B7FF';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM