我正在制作Bubble排序可视化算法,并希望使用线形图展示短路的过程。
我试图实现计算属性,但浏览器挂起。
<template>
<div class="hello">
<h1>Bubble Sort</h1>
<p>{{ bubbleSort()}}</p>
<line-chart :data="bubbleSort()"></line-chart>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
a : [12, 0, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213]
}
},
methods : {
bubbleSort: function () {
let swapped;
do {
swapped = false;
for(var i = 0; i < this.a.length; i++){
if(this.a[i] > this.a[i+1]){
let temp = this.a[i];
this.a[i] = this.a[i+1];
this.a[i+1] = temp;
swapped = true;
}
}
}while(swapped);
return Object.assign({},this.a);
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
</style>
我希望图表会在发生短路时更新。
答案 0 :(得分:0)
使用计算属性不是实现气泡排序可视化的最佳方法,原因有二:
a
时都会重新计算一次计算的属性,而您正在更改计算的属性本身中的a
的值;这可能是导致浏览器挂起的原因。由于您不是直接在模板中使用a
,并且计算属性只有一个依赖项a
,因此,摆脱计算属性就不需要了。
相反,创建一个函数以完成气泡排序算法的一次遍历,然后在setInterval
中调用该函数,并在进行0次交换遍历后取消循环:
export default {
name: 'HelloWorld',
data() {
return {
a : [12, 0, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213],
intervalId: null,
}
},
methods: {
bubbleSort() {
let swapped = false;
for (let i = 0; i < this.a.length - 1; i++) {
if (this.a[i] > this.a[i+1]) {
const temp = this.a[i];
this.$set(this.a, i, this.a[i+1]);
this.$set(this.a, i+1, temp);
swapped = true;
}
}
if (!swapped) {
clearInterval(this.intervalId);
}
},
},
mounted() {
this.intervalId = setInterval(() => {
this.bubbleSort();
}, 2000);
}
};
注意:
$set
。参见https://vuejs.org/v2/guide/list.html#Caveats。a
是一个非常难以描述的变量名,请尝试为其赋予一个更有意义和唯一的名称。swapp
。别那么懒。如果您对问题不屑一顾,那么没人会回答这个问题。