vue实现冒泡排序


实现思路
在Vue中实现冒泡排序,可以通过数据绑定和响应式特性动态展示排序过程。核心是将排序算法与Vue的data和methods结合,通过操作数组实现可视化效果。
核心代码示例
<template>
<div>
<button @click="startBubbleSort">开始排序</button>
<div class="array-container">
<div
v-for="(num, index) in array"
:key="index"
class="array-item"
:style="{ height: num * 10 + 'px' }"
>
{{ num }}
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
array: [5, 3, 8, 4, 2],
isSorting: false
};
},
methods: {
async startBubbleSort() {
if (this.isSorting) return;
this.isSorting = true;
let arr = [...this.array];
let n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
this.array = [...arr];
await new Promise(resolve => setTimeout(resolve, 500));
}
}
}
this.isSorting = false;
}
}
};
</script>
<style>
.array-container {
display: flex;
align-items: flex-end;
gap: 5px;
margin-top: 20px;
}
.array-item {
width: 40px;
background-color: #42b983;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
</style>
代码说明
- 数据绑定:使用
v-for动态渲染数组元素,通过:style绑定高度实现可视化效果。 - 排序逻辑:通过嵌套循环比较相邻元素,若顺序错误则交换位置。使用ES6解构赋值简化交换操作。
- 异步延迟:通过
setTimeout和Promise实现每一步的延迟,便于观察排序过程。 - 状态管理:
isSorting标志位防止重复触发排序。
扩展优化
- 动画增强:可添加CSS过渡效果或使用Vue的
<transition-group>让元素移动更平滑。 - 性能提示:对于大数据量排序,需考虑分块渲染或Web Worker避免界面卡顿。
- 交互控制:增加暂停、继续按钮,提升用户体验。
该实现通过Vue的响应式特性,将算法过程直观展示,适合教学或演示场景。实际项目中若需高效排序,建议直接使用Array.prototype.sort()。






