-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.js
More file actions
34 lines (31 loc) · 768 Bytes
/
insertionSort.js
File metadata and controls
34 lines (31 loc) · 768 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
function insertionSort(array) {
for (let i = 1; i < array.length; i++) {
insert(i, array);
}
}
function insert(n, array) {
const toSort = array[n];
let index = n;
while (index > 0) {
if (array[index - 1] < toSort) break;
array[index] = array[index - 1];
index--;
}
array[index] = toSort;
console.log(array);
}
// Given n and arr
function insertionSort2(n, arr) {
for (let i = 1; i < n; i++) {
const toSort = arr[i];
let index = i;
while (index > 0) {
if (arr[index - 1] < toSort) break;
arr[index] = arr[index - 1];
index--;
}
arr[index] = toSort;
console.log(arr.join(' '));
}
}
export default insertionSort;