用js和html实现冒泡排序的动画
时间: 2024-02-27 14:56:50 浏览: 78
js 排序动画模拟 冒泡排序
以下是使用 JavaScript 和 HTML 实现冒泡排序动画的示例代码:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Bubble Sort Animation</title>
<style>
#container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.bar {
width: 20px;
height: 100px;
margin: 0 5px;
background-color: blue;
}
</style>
</head>
<body>
<button onclick="startAnimation()">Start Animation</button>
<div id="container"></div>
<script src="bubbleSort.js"></script>
</body>
</html>
```
JavaScript 代码:
```
let container = document.getElementById('container');
let bars = [];
// Generate an array of random numbers and create bars for each number
for (let i = 0; i < 10; i++) {
let number = Math.floor(Math.random() * 100);
let bar = document.createElement('div');
bar.className = 'bar';
bar.style.height = number + 'px';
container.appendChild(bar);
bars.push(bar);
}
// Bubble sort algorithm
async function bubbleSort() {
let length = bars.length;
for (let i = 0; i < length; i++) {
for (let j = 0; j < (length - i - 1); j++) {
if (bars[j].offsetHeight > bars[j + 1].offsetHeight) {
await swapBars(bars[j], bars[j + 1]);
}
}
}
}
// Swap two bars and update their heights
function swapBars(bar1, bar2) {
return new Promise(resolve => {
let tempHeight = bar1.offsetHeight;
bar1.style.height = bar2.offsetHeight + 'px';
bar2.style.height = tempHeight + 'px';
setTimeout(() => {
resolve();
}, 100);
});
}
// Start the animation when the button is clicked
function startAnimation() {
bubbleSort();
}
```
该程序首先生成一个包含随机数字的数组,并为每个数字创建一个表示该数字的条形。然后,使用冒泡排序算法对这些条形进行排序,并在每次交换两个条形时更新它们的高度以反映它们的位置。最后,当用户点击按钮时,程序将开始动画并按顺序显示每个交换的步骤。
阅读全文