Insertion Sort
Algorithms
Insertion sort is a simple sorting algorithm that builds the sorted array one element at a time by inserting each element into its correct position.
Algorithm
The algorithm works similar to how we sort playing cards in our hands: we pick an element and insert it into its correct position in the already sorted portion.
Time Complexity
- Best case: (when array is already sorted)
- Average case:
- Worst case:
Implementation
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
# Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
# Example usage with different numbers
arr = [45, 23, 78, 12, 56, 89, 34]
sorted_arr = insertion_sort(arr)
print("Sorted array:", sorted_arr) Trace it by hand
ProblemRun insertion sort on a 5-element array
Insertion sort on [5, 2, 8, 1, 4]: write down the state of the array after each outer-loop pass (i.e., after each of the 4 insertions). Then count the total number of element shifts performed.
State after each pass:
- After processing index 1 (value 2):
[2, 5, 8, 1, 4]— one shift. - After processing index 2 (value 8):
[2, 5, 8, 1, 4]— no shifts (8 > 5). - After processing index 3 (value 1):
[1, 2, 5, 8, 4]— three shifts. - After processing index 4 (value 4):
[1, 2, 4, 5, 8]— two shifts.
Total: 6 shifts. Note that the "no shift" case at i=2 is what insertion sort exploits for the best-case running time on already-sorted input — on a perfectly sorted array, every pass does zero shifts.