Python Program for Insertion Sort with Example and Explanation
for and while loops; for example: for i in range(1, len(arr)): key = arr[i]; j = i-1; while j >= 0 and arr[j] > key: arr[j+1] = arr[j]; j -= 1; arr[j+1] = key.Examples
How to Think About It
Algorithm
Code
def insertion_sort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key # Example usage numbers = [5, 2, 9, 1] insertion_sort(numbers) print(numbers)
Dry Run
Let's trace the list [5, 2, 9, 1] through the insertion sort code.
Start with i=1 (value 2)
Compare 2 with 5; since 5 > 2, shift 5 right and insert 2 at position 0. List becomes [2, 5, 9, 1].
i=2 (value 9)
Compare 9 with 5; 5 < 9, so no shift needed. List stays [2, 5, 9, 1].
i=3 (value 1)
Compare 1 with 9, 5, 2; all are greater, shift them right. Insert 1 at position 0. List becomes [1, 2, 5, 9].
| Iteration | List State |
|---|---|
| i=1 | [2, 5, 9, 1] |
| i=2 | [2, 5, 9, 1] |
| i=3 | [1, 2, 5, 9] |
Why This Works
Step 1: Choosing the key element
The element at index i is chosen as the key to insert into the sorted part of the list.
Step 2: Shifting elements
Elements greater than the key are shifted one position to the right to make space for the key.
Step 3: Inserting the key
The key is placed in its correct sorted position, ensuring the left side of the list is sorted.
Alternative Approaches
arr = [5, 2, 9, 1] arr.sort() print(arr)
def recursive_insertion_sort(arr, n=None): if n is None: n = len(arr) if n <= 1: return recursive_insertion_sort(arr, n-1) last = arr[n-1] j = n-2 while j >= 0 and arr[j] > last: arr[j+1] = arr[j] j -= 1 arr[j+1] = last arr = [5, 2, 9, 1] recursive_insertion_sort(arr) print(arr)
Complexity: O(n^2) time, O(1) space
Time Complexity
Insertion sort uses nested loops; the outer loop runs n times and the inner loop can run up to n times in the worst case, resulting in O(n^2) time.
Space Complexity
It sorts the list in place without extra memory, so space complexity is O(1).
Which Approach is Fastest?
Built-in sort methods are faster for large data, but insertion sort is simple and efficient for small or nearly sorted lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Insertion Sort | O(n^2) | O(1) | Small or nearly sorted lists |
| Built-in sort | O(n log n) | O(n) | General purpose, large lists |
| Recursive insertion sort | O(n^2) | O(n) | Learning recursion, small lists |