Selection Sort

About

Imagine scanning a messy shelf of books to find the absolute shortest one, picking it up, and swapping its position with the very first book on the shelf. Then, you look at the remaining unsorted books, find the next shortest one, and swap it into the second position. Selection Sort repeatedly selects the minimum element from the unsorted portion of the array and moves it to the beginning.

![[sel.mp4]]

Complexities

Code Implementation

def selection_sort(arr):
    n = len(arr)
    
    # Move the boundary of the unsorted subarray
    for i in range(n):
        # Assume the first unsorted element is the minimum
        min_idx = i
        
        # Test against the rest of the array to find the true minimum
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
                
        # Swap the found minimum element with the first unsorted element
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
        
    return arr

Key Takeaways

Powered by Forestry.md