Loading...
Insertion Sort builds the sorted array one item at a time, shifting larger elements right to open a slot for the current key. It is efficient for small or nearly-sorted inputs (O(n) best case) and is the algorithm many standard libraries fall back to for tiny subarrays.
Inserts each element into its correct place among the already-sorted items.
| Best case | O(n) |
| Average case | O(n²) |
| Worst case | O(n²) |
| Space | O(1) |
| Stable | Yes |
Complexities are for the reference implementation shown; constant factors and cache behavior vary by language.
Idiomatic, copy-paste implementations. Pick your language:
Python
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
return arrSorting [5, 1, 4, 2] step by step:
The control flow of the algorithm as a diagram: