Skip to content

Commit 06b4e3f

Browse files
committed
Add insertion sort
1 parent 69f318d commit 06b4e3f

File tree

4 files changed

+26
-0
lines changed

4 files changed

+26
-0
lines changed
File renamed without changes.
File renamed without changes.
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
const insertionSort = (arr) => {
2+
for (let i = 0; i < arr.length; i++) {
3+
let currentVal = arr[i];
4+
let j = i - 1;
5+
6+
console.log('Before current:', currentVal, ', j: ', j, `[${arr[j]}]`);
7+
8+
while (j >= 0 && arr[j] > currentVal) {
9+
arr[j + 1] = arr[j];
10+
j--;
11+
console.log('lol', arr);
12+
}
13+
14+
// for (; j >= 0 && arr[j] > currentVal; j--) {
15+
// arr[j + 1] = arr[j];
16+
// }
17+
18+
arr[j + 1] = currentVal;
19+
console.log(arr);
20+
console.log('After current:', currentVal, ', j', j, `[${arr[j]}]`);
21+
}
22+
23+
return arr;
24+
};
25+
26+
console.log(insertionSort([1, 3, 2]));

0 commit comments

Comments
 (0)