算法--希尔排序可视化
一直都想做各种数据可视化
现用工具 echarts 做排序过程可视化
希尔排序
算法性能取决于 h
function shellSort(array) {
const N = array.length;
let h = 1;
while (h < N / 3) h = 3 * h + 1;
while (h >= 1) {
for (let i = h; i < N; i++) {
for (let j = i; j >= h && array[j] < array[j - h]; j -= h) {
let tem = array[j];
array[j] = array[j - h];
array[j - h] = tem;
process.push(arr.slice(0));
}
}
h = Math.floor(h / 3);
}
}
shellSort(arr);
其中 process 是用来存储过程的数组,每次变化的数组结果都存在该数组中,每次存入结果如下
希尔排序,将固定间隔的数形成多个数组,每个数组进行排序,间隔量从指定值缩小到 1 ,最后将多个数组合并成一个
Echarts
三部曲,设置 DOM 元素---初始化 Echarts---设置 Option
通过不断改变 option 中的数据来不断更新图表,最终形成动画
animationDuration: 0,
animationDurationUpdate: 1000,
animationEasing: "linear",
animationEasingUpdate: "linear",
// 在 option 中设置转换动画
播放动画
这里使用了 setInterval
函数来播放动画,将过程数组的长度作为标识符,如果长度大于零,那么取出来设置到 option
中,最终形成动画
完整代码如下
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.shell {
100%;
height: 100vh;
}
</style>
</head>
<body>
<div class="shell"></div>
<script src="./js/echarts.min.js"></script>
<script>
const arr = [88, 90, 30, 5, 45, 2, 34, 23, 45, 65, 64, 34, 34];
const dom = document.querySelector(".shell");
const myChart = echarts.init(dom);
const option = {
// 图表位置
grid: {
top: 10,
bottom: 30,
left: 100,
right: 80,
},
xAxis: {
type: "value",
},
yAxis: {
type: "category",
data: arr,
},
series: [
{
name: "number",
type: "bar",
data: arr,
label: {
show: true,
// position: "right",
valueAnimation: true,
},
},
],
animationDuration: 0,
animationDurationUpdate: 1000,
animationEasing: "linear",
animationEasingUpdate: "linear",
};
myChart.setOption(option);
const process = [];
// 希尔排序
function shellSort(array) {
const N = array.length;
let h = 1;
while (h < N / 3) h = 3 * h + 1;
while (h >= 1) {
for (let i = h; i < N; i++) {
for (let j = i; j >= h && array[j] < array[j - h]; j -= h) {
let tem = array[j];
array[j] = array[j - h];
array[j - h] = tem;
process.push(arr.slice(0));
}
}
h = Math.floor(h / 3);
}
}
shellSort(arr);
// 播放动画
const interval = setInterval(() => {
if (process.length === 0) {
clearInterval(interval);
} else {
const temArr = process.shift();
console.log(temArr);
option.yAxis.data = temArr;
option.series[0].data = temArr;
myChart.setOption(option);
}
}, 1000);
</script>
</body>
</html>