Insertion Sort in Python š
Like Sorting Cards
Insertion sort builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms.
š» Implementation
python
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
arr = [12, 11, 13, 5, 6]
insertion_sort(arr)
print(arr)š® Interactive Insertion Sort Demo
Speed:
ā¹ļø Ready
Comparing/Active
Sorted
š” Best Case
If the array is already sorted, time complexity is O(n). Average/Worst case is O(n²).