-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion-sort.js
More file actions
37 lines (34 loc) · 753 Bytes
/
insertion-sort.js
File metadata and controls
37 lines (34 loc) · 753 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
35
36
37
// insertion sort
// Time O(n^2) | Best O(n) "with a sorted array as input we get the best"
// Space O(1)
function insertionSort(array) {
for (let i = 1; i < array.length; i++) {
let j = i;
while (j > 0 && array[j] < array[j - 1]) {
swap(j, j - 1, array);
j--;
}
}
return array;
}
function swap(a, b, array) {
const temp = array[a];
array[a] = array[b];
array[b] = temp;
}
// variation with one-liner swap
//
// Time O(n) - Best Case
// Time O(n^2) - Worst Case
// Space O(1)
//
function insertionSort(array) {
for (let i = 1; i < array.length; i++) {
let j = i;
while (j > 0 && array[j] < array[j - 1]) {
[array[j], array[j - 1]] = [array[j - 1], array[j]];
j--;
}
}
return array;
}