Insertion sort is one of sorting algorithms, to better understand it, you could imagine you are playing cards.
Every time you get a new card, compare it with the existing ones, then put it in the right place. While you comparing, we start it from right to left.
The following pictures gives a demonstration of how this sort happended.
Implementation
Let’s start building our insertionSort
function.
step 1
1 | function insertionSort(arr) { |
It’s a best practice to save the array length in a variable.
step 2
1 | function insertionSort(arr) { |
We use a for loop to go over the array.
step 3
1 | function insertionSort(arr) { |
Save current value in a variable for comparison.
step 4
1 | function insertionSort(arr) { |
We set up an inner loop in order to put current value in the right place.
step 5
1 | function insertionSort(arr) { |
Finally assign the the value current
to the correct index position.
Complexity
Best case: n
Average: n2
Worst: n2
Memory: 1
Stable: Yes