Sort - ⤵️ Insertion sort

  • Elements on the left are always sorted.
  • Swap arr[i] with smaller neighbours till there is no more elements smaller than it.

img

1
2
3
4
5
6
7
8
9
10
function insertSort(arr) {
for (let i = 0; i < arr.length; i++) {
let j = i - 1;
while (j >= 0 && arr[j + 1] < arr[j]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
j--;
}
}
return arr;
}