Selection Sort

A simple O(n²) sorting algorithm with predictable behavior — and consistently poor performance.


Context

Selection sort is often taught alongside bubble and insertion sort.

Unlike them, it:


Core idea

Each iteration fixes exactly one element.


Properties


Implementation

class SelectionSort {
    void sort(int[] array) {
        for (var i = 0; i < array.length; i++) {
            var minIndex = i;
            
            for (var j = i + 1; j < array.length; j++) {
                if (array[j] < array[minIndex]) {
                    minIndex = j;
                }
            }
            
            if (minIndex != i) {
                var temp = array[i];
                array[i] = array[minIndex];
                array[minIndex] = temp;
            }
        }
    }
}