Insertion Sort, explained step by step
Insertion Sort is an intuitive algorithm that builds the final sorted array one item at a time. It iterates through the input array, consuming one element per iteration, and finds its correct position within the already sorted left-hand side of the array. It does this by shifting any larger elements to the right to make room for the new element, much like sorting playing cards in your hand.
Intuition: Like sorting playing cards — you pick one card at a time and slide it into the correct position among the cards you are already holding.
How it works
- Assume the first element (index 0) is already sorted.
- Pick the next element and store it in a temporary variable (key).
- Compare the key with the elements in the sorted portion (right to left).
- Shift elements that are greater than the key to the right.
- Insert the key into the correct position. Repeat for all elements.
Complexity
- Best: O(n)
- Average: O(n²)
- Worst: O(n²)
- Space: O(1)
- Stable: yes
When to use it
Small arrays or nearly-sorted arrays. O(n) best case for already-sorted input. Used as a subroutine in Timsort.
Interview questions
- What is the best-case time complexity of Insertion Sort?
- When would you prefer Insertion Sort over Merge Sort?
- Is Insertion Sort adaptive?