Sorting
Insertion Sort
Build the sorted prefix one item at a time, shifting larger values right until the current key can be inserted.
Algorithm
The checked-in replay follows the same small input and final output across all 21 DSA books, so this Python DSA implementation can be compared directly with the other languages.
Basic Implementation
basic.py
arr = [5, 1, 4, 2, 8]
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
print(arr)
Complexity
- Time: O(n^2) worst and average, O(n) best
- Space: O(1)
- Stable: yes
Implementation notes
- Python stores
arras one list object whose slots hold references to immutableintobjects. The sort mutates that same list with assignments likearr[j + 1] = arr[j]; it does not allocate a replacement list. key = arr[i]binds the current integer object to a local name while larger elements shift right. Thewhile j >= 0 and arr[j] > keyguard short-circuits before any negative-index read, and the comparison uses Python integer ordering.- GC is not part of the visible loop behavior because the replayed work is slot
reassignment inside the existing list. The trace shows each completed insert:
1before5, then shifting5for4, then shifting5and4for2.
sorted prefix
Positions before the scan index are already sorted.
shifting
Larger values move one slot right to make room for the key.