Inserion sort is an inplace sorting algorithm meaning it won't take any extra space to sort the array items. It works similar to the way you sort playing cards in your hand. Consider you are dealt 4 cards one after the other. You pick one and keep in your hand, after that for the next card (key) you compare with the one in your hand and place it accordingly and so on until all the cards are in your hand.
To sort an array of size n in ascending order:
- Iterate from second element, arr[1] to arr[n-1] over the array.
- Compare the current element (key) to its predecessor.
- If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
Given array is 12 11 13 5 6 7
Sorted array is 5 6 7 11 12 13