排序算法的可视化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>携程第三题-排序算法可视化展示</title>
</head>
<style>
    .container {
        position: relative;
    }

    .sort {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        width: 50px;
        height: 50px;
        border: 1px solid black;
        transition: 2s;
    }
</style>
<body>
<div class="container"></div>
<script>
    let arr = [5, 4, 8, 9, 6, 5, 4, 12, 3, 6, 7, 8, 56];
    let docFrag = document.createDocumentFragment();
    arr.forEach((value, index) => {
        let subDiv = document.createElement("div");
        subDiv.innerText = `${value}`;
        subDiv.classList.add("sort");
        subDiv.style.left = `${index * 60}px`;
        docFrag.appendChild(subDiv);
    });
    let containerDiv = document.querySelector(".container");
    containerDiv.appendChild(docFrag);

    let sortedElements = Array.prototype.slice.call(containerDiv.childNodes);
    console.log(arr);
    bubbleSort(arr);
    console.log(arr);

    function bubbleSort(items) {

        let len = items.length;
        let stop;
        let time = 0
        for (let i = 0; i < len; i++) {
            for (let j = 0, stop = len - i; j < stop; j++) {
                if (items[j] > items[j + 1]) {
                    swapArrElement(arr, j, j + 1);
                    setTimeout(() => {
                        swapDomText(sortedElements, j, j + 1);
                    }, time * 2000);
                    time++;
                }
            }
        }
        return items;
    }

    function swapArrElement(items, firstIndex, secondIndex) {
        // let _temp = items[firstIndex];
        // items[firstIndex]= items[secondIndex];
        // items[secondIndex] = _temp;
        [items[firstIndex], items[secondIndex]] = [items[secondIndex], items[firstIndex]];
    }

    function swapDomText(sortedElements, firstIndex, secondIndex) {
        debugger
        let _temp = sortedElements[firstIndex].innerText;
        sortedElements[firstIndex].innerText = sortedElements[secondIndex].innerText;
        sortedElements[secondIndex].innerText = _temp;

    }
</script>
</body>
</html>

总结:1、知识点要多用多练。学了就是要用,在使用中熟练。
2、体会绝对定位的作用,setTimeout的使用,脚本化样式表的强大。

    原文作者:排序算法
    原文地址: https://blog.csdn.net/u012207345/article/details/82493038
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞