I am creating a sorting visualizer and I already got some algorithms done: bubble, selection, insertion. I am trying to implement shell sort as well, but the sorting stops after 3 iterations through the entire array. Until that happens, the sorting process seems fine. Why does this happen? I can see it stopping because I update the chart after each iteration of the inner loop. Here is my code:
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();
}
}
}
Oh, never mind, the algorithm works fine, its just that since JavaScript has only the number type and not int, I have to explicitly do math.floor for each gap to get a whole number otherwise I would be accessing a floating point index which is not possible.