Insertion Sort
Efficient algorithm for sorting a small number of algorithms. If the array is sorted, the runtime is reduced to .
High Level Idea: We go from left to right.
- Find where
x
should go - Shift elements that are greater
x
- Insert
x
- Repeat
Insertion Sort Pseudocode#card
for i in range(1, len(A)):
j = i # scan backward from i.
while j > 0 and A[j - 1] > A[j]:
# swap out-of-order elements.
A[j], A[j - 1] = A[j - 1], A[j]
j -= 1
Time Complexity
- Best Case:
- Average Case:
- Worst Case:
Space Complexity
- Worst Case: