Insertion Sort

Insertion Sort Algorithm

Key Takeaways: Insertion Sort builds a sorted array one element at a time. It behaves exactly like how you might sort a hand of playing cards. It is highly efficient for small or nearly sorted datasets.

After learning Bubble Sort and Selection Sort, we move to our third foundational sorting algorithm: Insertion Sort.

This algorithm is very intuitive. It is the natural way humans tend to sort physical items!


1. How Does Insertion Sort Work?

Insertion Sort divides the array into a sorted part and an unsorted part, just like Selection Sort.

However, instead of looking for the smallest item, Insertion Sort simply picks up the very first unsorted item. It then scans backward through the sorted part and inserts the item into its exact correct position.

Real-Life Analogy

Imagine you are holding a hand of playing cards.

  1. You hold the first card in your left hand. It is already "sorted" because it's the only card.
  2. Your right hand picks up the next card from the deck.
  3. You compare it to the cards in your left hand.
  4. You slide it into the correct position.
  5. You repeat this until there are no cards left in the deck.
Visual representation of Insertion Sort placing elements into their sorted positions

Insertion Sort: Pick the next element and shift existing elements right to make room for it.


2. A Step-by-Step Example

Let's sort an array: [5, 3, 8, 4, 2]

Pass 1:

Pass 2:

Pass 3:

Pass 4:


3. Insertion Sort Code Example

Let's write the Insertion Sort algorithm in Python. Pay attention to the while loop that handles shifting the larger elements to the right!

Insertion Sort in Python

def insertion_sort(arr):
    # Start from 1, because index 0 is already "sorted"
    for i in range(1, len(arr)):
        key = arr[i] # The element we want to insert
        j = i - 1
        # Move elements that are greater than key
        # to one position ahead of their current position
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
        # Insert the key in its correct position
        arr[j + 1] = key
    return arr

numbers = [5, 3, 8, 4, 2] print("Original:", numbers) print("Sorted:", insertion_sort(numbers))


4. Time Complexity

Because of its O(n) best-case scenario, many modern programming languages actually use a hybrid of Insertion Sort and other algorithms (like Merge Sort) to handle small datasets under the hood!


Exercise 1 of 1

?

Why does Insertion Sort have an amazing Best Case Time Complexity of O(n)?