我正在创建一个排序可视化工具,并且已经完成了一些算法:冒泡、选择、插入。我也在尝试实现 shell 排序,但排序在整个数组的 3 次迭代后停止。在此之前,排序过程似乎很好。为什么会这样?我可以看到它停止了,因为我在内循环的每次迭代后更新了图表。这是我的代码:
async ShellSort(delay = 5) {
for (let gap = Math.floor(this.data.length / 2); gap > 0; gap /= 2) {
for (let i = gap; i < this.data.length; i++) {
let temp = this.data[i];
let j = i;
while (j > gap && temp < this.data[j - gap]) {
this.data[j] = this.data[j - gap];
j -= gap;
}
this.data[j] = temp;
//update the chart
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, delay)
);
this.draw();
}
}
}