Selection Sort
Explore how the selection sort algorithm repeatedly selects the smallest element from the unsorted portion and places it in its final position. Understand its fixed O(n^2) time complexity, in-place operation with O(1) space, advantages, limitations, and how it differs from bubble sort through a step-by-step JavaScript implementation.
Imagine a teacher arranging exam papers by score from lowest to highest. Instead of swapping neighbors over and over, the teacher looks through the unsorted pile, finds the lowest-scoring paper, and places it first. Then the teacher repeats the process for the remaining pile.
That is the core idea of selection sort: each pass selects the smallest remaining element and places it in its final position.
Selection sort is a comparison-based sorting algorithm that repeatedly finds the minimum element from the unsorted portion of the collection and swaps it with the first unsorted position.
Main idea: Bubble sort pushes the largest value rightward using many adjacent swaps. Selection sort does something different: it scans the remaining unsorted section, picks the minimum once, then performs one swap at the end of the pass.
How selection sort works
Start at index
i = 0. Assume the current position holds the minimum element.Scan indices
i + 1to the end, updating the minimum index whenever a smaller value is found.After the scan finishes, swap the minimum element into position
i.Increment
iand repeat the same process for the remaining unsorted portion.
Interactive animation
In this visualizer, yellow marks the current minimum, purple marks the value currently being scanned, red shows the swap, and green shows positions that are already fixed.
Algorithm
The algorithm below shows how selection sort finds and places the minimum element at each step.
Start from the beginning of the list.
For each position
ifrom0ton - 1:Assume the current position contains the smallest element.
Keep track of its index as the minimum index.
Scan the remaining portion of the list (from
i + 1ton - 1):Compare each element with the current minimum.
If a smaller element is found:
Update the minimum index.
After scanning all remaining elements:
Swap the element at the current position with the element at the minimum index.
Step-by-step trace
Let’s trace selection sort on