Selection Sort — Definition, Formula & Example
Selection sort is a sorting algorithm that scans the unsorted part of a list, finds the smallest item, and swaps it into the next position at the front. It repeats this until the whole list is in order.
Given an array , for each , find an index with and swap with . After pass , the prefix is sorted and holds the smallest elements. This is the loop invariant that proves the algorithm correct. Selection sort makes exactly comparisons on every input, so its running time is . It performs at most swaps and sorts in place. The standard array version is not stable.
Key Formula
Where:
- = Number of comparisons selection sort makes on a list of length n
- = Number of items in the list
Worked Example
Problem: Use selection sort to put the list [8, 3, 6, 1, 5] in increasing order. Count the comparisons it makes.
Step 1: Pass 1 scans all five items. The minimum is 1, so swap it with 8 in the first position. Pass 2 scans [3, 6, 8, 5]. The minimum is 3, which is already in place, so no swap is needed.
Step 2: Pass 3 scans [6, 8, 5]. The minimum is 5, so swap it with 6. Pass 4 scans [8, 6]. The minimum is 6, so swap it with 8. The last item is now in place automatically.
Step 3: Count the comparisons. Pass compares across the unsorted items, which takes comparisons.
Answer: The sorted list is [1, 3, 5, 6, 8]. It took 4 passes, 10 comparisons, and 3 actual swaps.
Why It Matters
In a first data structures or algorithms course, selection sort is often the first algorithm you analyze with a loop invariant and a count. It uses at most swaps, so it can make sense when writing to memory is costly, as with flash storage. The same greedy rule of "take the best remaining choice" drives Prim's algorithm for minimum spanning trees.
Common Mistakes
Mistake: Calling selection sort "sinking sort" or treating it as the same algorithm as bubble sort.
Correction: "Sinking sort" is a standard alternate name for bubble sort, not selection sort. Bubble sort swaps adjacent out-of-order pairs many times per pass. Selection sort finds the minimum first and then makes at most one swap per pass.
