0

我正在创建一个排序可视化工具,并且已经完成了一些算法:冒泡、选择、插入。我也在尝试实现 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();

      }

    }
  }
4

1 回答 1

0

哦,没关系,算法工作得很好,只是因为 JavaScript 只有数字类型而不是 int,我必须明确地为每个间隙做 math.floor 以获得一个整数,否则我将访问一个浮点索引不可能。

于 2020-05-16T00:13:07.157 回答