我正在尝试使排序算法可视化,以了解有关排序算法以及Genereal中Angular和TypeScript编码的更多信息。
我目前正在快速排序,并且排序算法可以正常工作,但是无法在客户端显示视觉效果。我的排序代码如下:
performQuickSort(arr, min, max) {
if (min >= max) { return; }
let i = min;
let j = max;
const pivot = arr[Math.trunc((min + max) / 2)];
while (i < j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
this._swap(arr, i, j);
}
this.performQuickSort(arr, min, i);
this.performQuickSort(arr, i + 1, max);
}
_swap(arr, min, max) {
if (min === max) { return; }
const temp = arr[min];
arr[min] = arr[max];
arr[max] = temp;
}
我已经尝试过使用setTimeout()并在内部执行交换操作,但延迟为1秒,但是它不起作用,因为我认为外部while循环执行得太快并导致连续的一秒延迟。
有谁知道如何在两次交换之间获得1秒的间隔,以便可以直观地看到排序?
提前致谢。
我已经尝试过使用setTimeout()并在内部执行交换操作,但延迟为1秒,但是它不起作用,因为我认为外部while循环执行得太快并导致连续的一秒延迟。
好吧,setTimeout()
异步执行,因此在_swap
执行之前,它之后的下一行(this._swap()
)将立即使用_swap()
执行前的值执行:
//These get executed before your _swap if you put your _swap under a setTimeout
this.performQuickSort(arr, min, i);
this.performQuickSort(arr, i + 1, max);
所以尝试把它们放进去 setTimeout()
setTimeout(()=>{
this.performQuickSort(arr, min, i);
this.performQuickSort(arr, i + 1, max);
}, 1000);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句