SwadhyAI Notes

All Python notes

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²).