通过 HTML、CSS 和 JS 实现冒泡排序的示例
当然!下面是一个简单的示例,展示如何使用 HTML、CSS 和 JavaScript 实现冒泡排序。这个示例包括一个简单的布局和按钮,用于演示数组的排序过程。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bubble Sort Visualization</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 50px;
background-color: #f4f4f4;
}
#array {
display: flex;
margin-bottom: 20px;
}
.bar {
width: 20px;
margin: 0 2px;
background-color: #3498db;
text-align: center;
color: white;
}
.bar.active {
background-color: #e74c3c;
}
button {
padding: 10px 20px;
background-color: #2ecc71;
color: white;
border: none;
cursor: pointer;
margin-top: 20px;
}
button:disabled {
background-color: #95a5a6;
}
</style>
</head>
<body>
<div id="array"></div>
<button id="sortBtn">Sort</button>
<script>
const array = [64, 34, 25, 12, 22, 11, 90];
const arrayContainer = document.getElementById('array');
const sortBtn = document.getElementById('sortBtn');
function createBars() {
arrayContainer.innerHTML = '';
for (let i = 0; i < array.length; i++) {
const bar = document.createElement('div');
bar.style.height = `${array[i] * 3}px`;
bar.classList.add('bar');
bar.innerText = array[i];
arrayContainer.appendChild(bar);
}
}
async function bubbleSort() {
let bars = document.querySelectorAll('.bar');
for (let i = 0; i < bars.length - 1; i++) {
for (let j = 0; j < bars.length - i - 1; j++) {
bars[j].classList.add('active');
bars[j + 1].classList.add('active');
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, 500)
);
if (array[j] > array[j + 1]) {
const temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
bars[j].style.height = `${array[j] * 3}px`;
bars[j + 1].style.height = `${array[j + 1] * 3}px`;
bars[j].innerText = array[j];
bars[j + 1].innerText = array[j + 1];
}
bars[j].classList.remove('active');
bars[j + 1].classList.remove('active');
}
}
sortBtn.disabled = false;
}
createBars();
sortBtn.addEventListener('click', () => {
sortBtn.disabled = true;
bubbleSort();
});
</script>
</body>
</html>
说明
- HTML:在
body
中包含一个用于展示数组元素的div
和一个排序按钮。 - CSS:样式使得数组元素呈现为垂直柱状条,
active
类用于标记正在比较的元素。 - JavaScript:实现了一个简单的冒泡排序算法。在
bubbleSort
函数中,使用setTimeout
模拟动画效果。按钮点击后开始排序,排序完成后启用按钮。
将以上代码复制到一个 HTML 文件中并在浏览器中打开,即可看到冒泡排序的可视化效果。每次点击按钮都会对数组重新进行排序,并显示排序过程。