📜  使用JavaScript进行冒泡排序可视化

📅  最后修改于: 2021-04-17 15:56:11             🧑  作者: Mango

GUI(图形用户界面)比程序更能帮助您理解。在本文中,我们将使用JavaScript可视化冒泡排序。我们将看到在Bubble Sort中如何交换元素以及如何获得最终的排序数组。我们还将可视化冒泡排序的时间复杂度。

参考:

  • 泡泡排序
  • JavaScript中的异步函数

方法:

  • 首先,我们将使用Math.random()函数生成一个随机数组。
  • 不同的颜色用于指示要比较,排序排序的元素
  • 由于该算法执行操作非常快,因此已使用setTimeout()函数来减慢该过程。
  • 可以通过按“ Ctrl + R”键来生成新数组。
  • 使用BubbleSort()函数和swap()函数执行排序

例子:

以下是可视化冒泡排序算法的程序。

index.html

HTML


  

    
    
    

  

    
    

Bubble Sort

       
       


style.css:以下是上述文件中使用的“ style.css”的内容。

* {
    margin: 0px;
    padding: 0px;
    box-sizing: border-box;
}
  
.header {
    font-size: 20px;
    text-align: center;
}
  
#array {
    background-color: white;
    height: 413px;
    width: 598px;
    margin: auto;
    position: relative;
    margin-top: 64px;
}
  
.block {
    width: 28px;
    background-color: #6b5b95;
    position: absolute;
    bottom: 0px;
    transition: 0.2s all ease;
}
  
.block_id {
    position: absolute;
    color: black;
    margin-top: -20px;
    width: 100%;
    text-align: center;
}

script.js:以下是上述HTML代码中使用的“ script.js”文件的内容。

var container = document.getElementById("array");
  
// Function to generate the array of blocks
function generatearray() {
    for (var i = 0; i < 20; i++) {
  
        // Return a value from 1 to 100 (both inclusive)
        var value = Math.ceil(Math.random() * 100);
  
        // Creating element div
        var array_ele = document.createElement("div");
  
        // Adding class 'block' to div
        array_ele.classList.add("block");
  
        // Adding style to div
        array_ele.style.height = `${value * 3}px`;
        array_ele.style.transform = `translate(${i * 30}px)`;
  
        // Creating label element for displaying 
        // size of particular block
        var array_ele_label = document.createElement("label");
        array_ele_label.classList.add("block_id");
        array_ele_label.innerText = value;
  
        // Appending created elements to index.html 
        array_ele.appendChild(array_ele_label);
        container.appendChild(array_ele);
    }
}
  
// Promise to swap two blocks
function swap(el1, el2) {
    return new Promise((resolve) => {
  
        // For exchanging styles of two blocks
        var temp = el1.style.transform;
        el1.style.transform = el2.style.transform;
        el2.style.transform = temp;
  
        window.requestAnimationFrame(function() {
  
            // For waiting for .25 sec
            setTimeout(() => {
                container.insertBefore(el2, el1);
                resolve();
            }, 250);
        });
    });
}
  
// Asynchronous BubbleSort function
async function BubbleSort(delay = 100) {
    var blocks = document.querySelectorAll(".block");
  
    // BubbleSort Algorithm
    for (var i = 0; i < blocks.length; i += 1) {
        for (var j = 0; j < blocks.length - i - 1; j += 1) {
  
            // To change background-color of the
            // blocks to be compared
            blocks[j].style.backgroundColor = "#FF4949";
            blocks[j + 1].style.backgroundColor = "#FF4949";
  
            // To wait for .1 sec
            await new Promise((resolve) =>
                setTimeout(() => {
                    resolve();
                }, delay)
            );
  
            console.log("run");
            var value1 = Number(blocks[j].childNodes[0].innerHTML);
            var value2 = Number(blocks[j + 1]
                        .childNodes[0].innerHTML);
  
            // To compare value of two blocks
            if (value1 > value2) {
                await swap(blocks[j], blocks[j + 1]);
                blocks = document.querySelectorAll(".block");
            }
  
            // Changing the color to the previous one
            blocks[j].style.backgroundColor = "#6b5b95";
            blocks[j + 1].style.backgroundColor = "#6b5b95";
        }
  
        //changing the color of greatest element 
        //found in the above traversal
        blocks[blocks.length - i - 1]
                .style.backgroundColor = "#13CE66";
    }
}
  
// Calling generatearray function
generatearray();
  
// Calling BubbleSort function
BubbleSort();

输出: