1

I have async insertsort function and my problem is that I am not able to insert

async function InsertSort(delay = 100) {
    var blocks = document.querySelectorAll(".block");

    // InsertSort Algorithm
    for (var i = 0; i < blocks.length; i += 1) {
        var current = blocks[i];
        var minindex = i

        // To change background-color of the
        // blocks to be compared
        current.style.backgroundColor = "#FF4949";
        
        for (var j = i+1; j < blocks.length; j += 1) {

            // To change background-color of the
            // blocks to be compared
            blocks[j].style.backgroundColor = "#FF4949";

            // To wait for .1 sec
            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, delay)
                );

            console.log("run");
            var value1 = Number(current.childNodes[0].innerHTML);
            var value2 = Number(blocks[j].childNodes[0].innerHTML);

            // To compare value of two blocks
            if(value1 > value2) {
                current.style.backgroundColor = "#6b5b95";
                current = blocks[j]
                minindex = j
                current.style.backgroundColor = "#37c59a";
            } else{
                blocks[j].style.backgroundColor = "#6b5b95";
            }
        }

        //changing the color of smallest element
        blocks[i].style.backgroundColor = "#13CE66";
    }

I am able to highlight smallest element, but not able to make new function insertswap(smallest_element, array) to insert smallest element into the right place. One option is to use Promise object, but I couldn't make it work.

Vilo1
  • 11
  • 3
  • FWIW, [doing it with a generator function and `requestAnimationFrame`](https://stackoverflow.com/questions/61884893/java-script-sorting-algorithm-visualizer). – T.J. Crowder Nov 25 '21 at 12:58

0 Answers0