用html+css+JavaScript实现的极为简单的选择排序可视化的dome版本
(开袋即食的dome)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test</title>
<style>
* {
margin: 0;
padding: 0;
}
.w {
width: 1200px;
height: 2000px;
margin: 0 auto;
background-color: rgb(250, 250, 250);
}
.ele {
display: inline-block;
background-color: yellowgreen;
width: 20px;
/* height: 20px; */
line-height: 20px;
padding: 10px;
margin: 5px;
}
.next {
width: 90px;
height: 20px;
background-color: skyblue;
margin: 10px;
padding: 10px;
line-height: 20px;
cursor: pointer;
user-select: none
}
</style>
</head>
<body>
<div class="w">
<ul id="sort">
</ul>
<div id="next" class="next">
next step
</div>
</div>
<script>
var s = document.getElementById('sort');
var list = []
var length = 17;
for (var i = 0; i < length; i++) {
list[i] = (88 + i * i * i) % 29;
}
var next = document.getElementById('next');
var li = []
for (var i = 0; i < length; i++) {
li[i] = document.createElement('li');
li[i].innerText = list[i];
li[i].style.height = list[i] * 7 + 'px'
li[i].className = 'ele';
s.appendChild(li[i])
}
f = true;
next.onclick = function () {
if (f == true) {
selectSort(left);
f = false;
} else {
swap(left, right);
left++;
f = true;
}
}
// 选择排序
var left = 0;
var right;
function selectSort(left) {
var max = left;
for (var j = left + 1; j < length; j++) {
if (list[j] > list[max]) {
max = j;
}
}
li[max].style.backgroundColor = 'skyblue';
right = max;
}
// 交换函数
function swap(a, b) {
var t2 = list[a];
list[a] = list[b];
list[b] = t2;
li[b].innerText = list[b];
li[b].style.height = list[b] * 7 + 'px';
li[b].style.backgroundColor = 'yellowgreen';
li[a].innerText = list[a];
li[a].style.height = list[a] * 7 + 'px'
li[a].style.backgroundColor = 'skyblue';
}
// 生成一组li
function createLi() {
for (var j = 0; j < length; j++) {
li[j] = document.createElement('li');
li[j].innerText = list[j];
li[j].style.height = list[j] * 7 + 'px'
li[j].className = 'ele';
s.appendChild(li[j])
}
}
</script>
</body>
</html>