Skip to content

Commit 84a21a3

Browse files
authored
Create insertion-sort.js
1 parent c1e8ce7 commit 84a21a3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

insertion-sort.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const shiftElements = (array, from, to) => {
2+
const toElement = array[to];
3+
while (to != from) {
4+
array[to] = array[to - 1];
5+
--to;
6+
}
7+
array[from] = toElement;
8+
};
9+
10+
const insertionSort = array => {
11+
let iterations = 0;
12+
let i = 0,
13+
j;
14+
while (i < array.length - 1) {
15+
j = 0;
16+
const toCompare = i + 1;
17+
while (j <= i) {
18+
iterations++;
19+
if (array[toCompare] < array[j]) {
20+
shiftElements(array, j, toCompare);
21+
break;
22+
}
23+
j++;
24+
}
25+
i++;
26+
console.log("array is now: " + array);
27+
}
28+
console.log(iterations);
29+
};
30+
31+
const array = [-31, 1, 0, 83, 4];
32+
insertionSort(array);
33+
console.log(array);

0 commit comments

Comments
 (0)