Skip to content

Commit d1e39f8

Browse files
Insertion sort using binary search instead of linear
1 parent 6e81685 commit d1e39f8

File tree

1 file changed

+34
-16
lines changed

1 file changed

+34
-16
lines changed

scripts/insertionSort.js

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,63 @@
22
class InsertionSort extends Sort {
33
constructor() {
44
super();
5-
this.index = 1;
65
this.done = 0;
76
this.comparing = 0;
7+
this.low = 0;
8+
this.high = 0;
89
}
910

1011
step() {
11-
if (this.done === arrayToSort.length - 1) {
12+
if (this.done === arrayToSort.length) {
1213
return true;
1314
}
14-
if (getValue(arrayToSort, this.index, false) > getValue(arrayToSort, this.comparing)) {
15-
move(this.index, this.comparing + 1, arrayToSort);
16-
this.done++;
17-
this.index = this.done + 1;
18-
this.comparing = this.done;
19-
} else if (this.comparing === 0) {
20-
move(this.index, 0, arrayToSort);
15+
16+
if (this.low >= this.high) {
17+
move(this.done, this.low, arrayToSort);
2118
this.done++;
22-
this.index = this.done + 1;
23-
this.comparing = this.done;
19+
this.low = 0;
20+
this.high = this.done;
21+
return false;
22+
}
23+
24+
const mid = Math.floor((this.low + this.high) / 2);
25+
let value = getValue(arrayToSort, mid);
26+
let compare = getValue(arrayToSort, this.done, false);
27+
if (compare < value) {
28+
this.high = mid;
29+
} else if (compare > value) {
30+
this.low = mid + 1;
2431
} else {
25-
this.comparing--;
32+
this.low = mid;
33+
this.high = mid;
2634
}
35+
return false;
2736
}
2837

2938
draw(cnt) {
3039
cnt.fillStyle = "#000";
3140
cnt.fillRect(0, 0, cnt.canvas.width, cnt.canvas.height);
3241
const sizeOfBlock = cnt.canvas.width / arrayToSort.length;
3342
arrayToSort.forEach((element, index) => {
34-
if (index === this.index) {
43+
cnt.fillStyle = "#c6d618";
44+
cnt.fillRect((this.high+1) * sizeOfBlock, 0, 1, cnt.canvas.height);
45+
cnt.fillStyle = "#d6a318";
46+
cnt.fillRect(this.low * sizeOfBlock, 0, 1, cnt.canvas.height);
47+
48+
if (index === this.done) {
3549
cnt.fillStyle = "#0e66c9";
36-
} else if (index === this.comparing) {
50+
}else if(index === this.low && index === this.high){
51+
cnt.fillStyle = "#c54816";
52+
} else if (index === this.low) {
3753
cnt.fillStyle = "#c6d618";
38-
} else if (index <= this.done) {
54+
} else if (index === this.high) {
55+
cnt.fillStyle = "#d6a318";
56+
} else if (index < this.done) {
3957
cnt.fillStyle = "#35d618";
4058
} else {
4159
cnt.fillStyle = getColorBasedOnValue(element);
4260
}
43-
cnt.fillRect(index * sizeOfBlock + sizeOfBlock * 0.025, 0, sizeOfBlock * 0.99, cnt.canvas.height * element);
61+
cnt.fillRect(index * sizeOfBlock + sizeOfBlock * 0.05, 0, sizeOfBlock * 0.99, cnt.canvas.height * element);
4462
});
4563
}
4664
}

0 commit comments

Comments
 (0)