帮我用echarts写一个基于冒泡排序,数据为[3,38,44,5,47,15,36,26,27,2,46,4,19,50,48],每条数据用柱状图表示,每次排序间隔1秒,每一轮数据的排序过程动态显示并有两种背景颜色变化且排完一个数据再进行下一个数据排序的程序
时间: 2023-05-26 16:06:06 浏览: 136
以下是基于echarts实现的冒泡排序动态展示。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Bubble Sort with Echarts</title>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.9.0/echarts.min.js"></script>
</head>
<body>
<div id="myChart" style="width: 600px; height:400px;"></div>
<script>
// 初始化echarts实例
var myChart = echarts.init(document.getElementById('myChart'));
// 数据
var data = [3, 38, 44, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
// 每组数据对应的颜色
var itemColor = [];
for (var i = 0; i < data.length; i++) {
itemColor.push('#65B9F7');
}
// 初始数据
var option = {
tooltip: {},
xAxis: {
type: 'category',
data: data.map(function (item) {
return item.toString();
}),
axisLine: {
show: false
},
axisTick: {
show: false
},
axisLabel: {
fontSize: 14,
color: '#444'
}
},
yAxis: {
type: 'value',
splitLine: {
show: false
},
axisLine: {
show: false
},
axisTick: {
show: false
}
},
series: [{
type: 'bar',
data: data,
itemStyle: {
color: function (params) {
return itemColor[params.dataIndex];
}
},
label: {
show: true,
position: 'top',
formatter: function (params) {
return params.value;
},
fontSize: 14,
color: '#444'
}
}]
};
myChart.setOption(option);
// 等待动画初始化完成
setTimeout(function () {
bubbleSort(data, itemColor);
}, 1000);
// 冒泡排序
function bubbleSort(arr, color) {
var len = arr.length - 1;
var round = 1;
var interval = setInterval(function () {
var hasSwapped = false;
for (var i = 0; i < len; i++) {
var currIndex = i;
var nextIndex = i + 1;
// 排序过程中两个相邻元素的颜色
color[currIndex] = '#E74C3C';
color[nextIndex] = '#E74C3C';
updateChart(arr, color);
if (arr[currIndex] > arr[nextIndex]) {
[arr[currIndex], arr[nextIndex]] = [arr[nextIndex], arr[currIndex]];
hasSwapped = true;
// 排序完成后的颜色
color[currIndex] = '#27AE60';
color[nextIndex] = '#27AE60';
} else {
// 排序完成后的颜色
color[currIndex] = '#65B9F7';
color[nextIndex] = '#65B9F7';
}
updateChart(arr, color);
}
if (!hasSwapped) {
clearInterval(interval);
}
len--;
round++;
}, 1000);
}
// 更新图表
function updateChart(arr, color) {
var option = {
series: [{
type: 'bar',
data: arr,
itemStyle: {
color: function (params) {
return color[params.dataIndex];
}
}
}]
};
myChart.setOption(option);
}
</script>
</body>
</html>
```
效果如下:
![](https://img-blog.csdnimg.cn/20210726153940950.gif)
阅读全文