浅谈JavaScript实现可视化展示冒泡排序过程

2020-4-4    seo达人



<!DOCTYPE html>

<html>

<head>

<title>JavaScript实现可视化展示冒泡排序过程</title>

<style>

#boxes{

border:1px solid grey;

width:1320px;

height:300px;

margin-top:10px;

position:relative;

}

.box{

background:red;

width:20px;

line-height:30px;

text-align:center;

font-family:Microsoft Yahei;

font-size:15px;

color:white;

margin:0 1px;

position:absolute;

}

</style>

</head>

<body>

<div id="boxes"></div>

<script>

function random(){

var numbers = [];

for (var i = 0; i < 60; i++) {

var number = Math.floor(Math.random() 90 + 10);

numbers.push(number);

var divElement = document.createElement("div");

var parentElement = document.getElementById("boxes");

divElement.style.left = i
20 + i 2 + "px";

divElement.style.top = 300 - 3
number + "px";

divElement.style.height = 3 number + "px";

divElement.setAttribute("class","box");

parentElement.appendChild(divElement);

}

return numbers;

}

function sort(){

var numbers = random();

var parentElement = document.getElementById("boxes");

var i = 0, j = 0;

var time = setInterval(function() {

if (i < numbers.length) {

if (j < numbers.length - i) {

if (numbers[j] > numbers[j + 1]) {

var temp = numbers[j];

numbers[j] = numbers[j + 1];

numbers[j + 1] = temp;

parentElement.innerHTML = "";

for (var k = 0; k < numbers.length; k++) {

var textNode = document.createTextNode(numbers[k]);

var divElement = document.createElement("div");

divElement.appendChild(textNode);

divElement.style.left = k
20 + k 2 + "px";

divElement.style.top = 300 - 3
numbers[k] + "px";

divElement.style.height = 3 * numbers[k] + "px";

divElement.setAttribute("class","box");

parentElement.appendChild(divElement);

}

}

j++;

}

else{

i++;

j = 0;

}

}

else {

clearInterval(time); 

return;

}

}, 100);  

}

sort();

</script>

</body>

</html>

————————————————

版权声明:本文为CSDN博主「筱葭」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/zhouziyu2011/java/article/details/53899692

分享本文至:

日历

链接

个人资料

蓝蓝设计的小编 http://www.lanlanwork.com

存档