xamples
epeat
ode
pproach
ptimize
est
Can you implement the insertion sort algorithm?
Given the array: [4, 2, 6, 2, 3]
The insertionSort function should return: [2, 2, 3, 4, 6]
Data is divided into sorted and unsorted portions. One by one, the unsorted values are inserted into their appropriate positions in the sorted subarray
'use strict'
function insertionSort(arr){
for(let i = 1; i < arr.length; i++){
let j = i;
while(arr[j-1] > arr[j] && j > 0){
let temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
return arr;
}
In the best case the array will already be sorted, but we have to look at each element to recognize that, thus O(n)
In the worst case the array will be reversed and we will have to touch each element n times, thus O(n^2)
The array is sorted in place, thus there is only constant O(1) additional space required
Interesting Fact: When people manually sort cards in bridge, they typically use a method similar to insertion sort