Selection Sort explained step-by-step: finding the minimum unsorted element, swapping into place, O(n²) comparison overhead with minimal O(n) writes, stability analysis, and code.
Selection Sort divides the input list into two parts: a sorted sublist that is built up from left to right at the front of the array, and a sublist of the remaining unsorted items. On each pass, the algorithm finds the smallest element from the unsorted sublist and swaps it with the leftmost unsorted element, moving the sublist boundary one position to the right.
A key feature of Selection Sort is that it makes at most n - 1 swaps total (O(n) writes). This makes it valuable in memory-constrained embedded systems (like Flash memory or EEPROMs) where memory writes are significantly more expensive than memory reads. However, because it performs n(n - 1)/2 comparisons regardless of the initial order, its time complexity is strictly O(n²) in all cases (best, worst, and average), and it is not a stable sort.
Scan the unsorted portion of the array (from index i to n - 1) and record the index of the minimum value.
If the minimum element is not already at index i, swap arr[i] with arr[minIdx] to place it in its correct sorted position.
Increment i by 1, expanding the sorted prefix and shrinking the unsorted suffix.
After n - 1 iterations, the final remaining element is naturally the largest and already in place.
1function selectionSort(arr) {2 const n = arr.length;3 4 for (let i = 0; i < n - 1; i++) {5 let minIdx = i;6 7 // Find the smallest element in the unsorted portion8 for (let j = i + 1; j < n; j++) {9 if (arr[j] < arr[minIdx]) {10 minIdx = j;11 }12 }13 14 // Swap it into its final sorted position (at most 1 swap per pass)15 if (minIdx !== i) {16 [arr[i], arr[minIdx]] = [arr[minIdx], arr[i]];17 }18 }19 20 return arr;21}22 23// Example usage:24// selectionSort([29, 10, 14, 37, 13]); // [10, 13, 14, 29, 37]Play through every comparison, swap, and state change, adjust the speed, or enter custom inputs to test edge cases.
The full interactive roadmap is unlocking — these specialized modules land in upcoming releases.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
This feature will be implemented in the next update.
Explore the full catalog — 30+ algorithms with more unlocking every release.
Ready — press Play or use step controls to walk through the algorithm.
Comparisons
0
Swaps / Shifts
0
Passes / Depth
0
Elements
10
Test your understanding of Selection Sort complexity and step mechanics.
Q1.How many swaps does Selection Sort perform in the worst case for an array of size n?
Q2.Why is standard array-based Selection Sort not stable?
Apply Selection Sort to real coding interview questions.
Find the kth largest element in an unsorted array.