Selection Sort

Selection Sort is a simple comparison-based sorting algorithm. It divides the input list into two parts: the sorted part at the front and the unsorted part at the back. On each pass, it selects the smallest (or largest) element from the unsorted part and swaps it with the first unsorted element, growing the sorted part by one.

Selection Sort is easy to understand and implement, but it is not adaptive and always performs the same number of comparisons, regardless of the initial order of the list. It is generally slower than more advanced algorithms for large datasets.

Its main advantage is simplicity and minimal memory usage, as it only requires a constant amount of additional space.

Time Complexity

CaseTime Complexity
BestO(n²)
AverageO(n²)
WorstO(n²)

Code Examples

# Python - selection sort
def selection_sort(arr):
    n = len(arr)
    for i in range(n):
        min_idx = i
        for j in range(i+1, n):
            if arr[j] < arr[min_idx]:
                min_idx = j
        arr[i], arr[min_idx] = arr[min_idx], arr[i]
    return arr