Selection Sort

Algorithms

Selection sort is a simple sorting algorithm that repeatedly finds the minimum element from the unsorted portion and places it at the beginning.

Algorithm

The algorithm maintains two subarrays: the sorted subarray and the unsorted subarray. In each iteration, it finds the minimum element from the unsorted subarray and swaps it with the first element of the unsorted subarray.

Time Complexity

Selection sort has a time complexity of in all cases, where is the number of elements.

Implementation

def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        # Find the minimum element in the remaining unsorted array
        min_idx = i
        for j in range(i + 1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        # Swap the found minimum element with the first element of the unsorted portion
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr

# Example usage with different numbers
arr = [45, 23, 78, 12, 56, 89, 34]
sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)

Trace it by hand

ProblemTrace the first two rounds of selection sort
Run selection sort on [29, 10, 14, 37, 13]. What is the array after round 1 (finding the min of the whole array and swapping it to position 0)? After round 2?