Data is divided into sorted and unsorted portions. One by one, the unsorted values are inserted into their appropriate positions in the sorted subarray
PseudoCode
Visual Representation
One Possible Solution
'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;
}
Efficiency
Time Efficiency in best case: O(n)
Time Efficiency in worst case: O(n^2)
Space Efficiency: O(1)
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