Insertion Sort

About

Insertion Sort builds a sorted array one element at a time. It splits the array into a "sorted" part on the left and an "unsorted" part on the right. It takes the next element from the unsorted side, shifts larger elements in the sorted side out of the way, and inserts it into its correct position—exactly like sorting a hand of playing cards as you are dealt one card at a time.

![[ins.mp4]]

Complexities

Code Implementation

def insertion_sort(arr):
    # Loop from the second element (index 1) to the end
    for i in range(1, len(arr)):
        key = arr[i] # The element we want to insert into the sorted part
        j = i - 1
	    
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]  # Shift element to the right
            j -= 1
            
        # Place the key at its correct sorted position
        arr[j + 1] = key
        
    return arr

Key Takeaways

Powered by Forestry.md