Selection Sort: Solution and Explanation
Given an array of integers, sort it in ascending order using selection sort. The algorithm repeatedly finds the smallest value in the unsorted part of the array and moves it to the front of that part, sorting in place.
Watch it run step by step
Try your own input and write the code →Intuition
Think about how you might sort a hand of cards laid out on a table. A natural strategy is to scan all of them, pick up the smallest, and put it in the first position. Then scan what is left, pick up the next smallest, and put it in the second position. Keep going until nothing is left. That is selection sort, and it maps directly onto an array: the left side grows as a sorted prefix, and the right side is the pool you keep selecting from.
The invariant that makes it correct is simple. After iteration i, the first i + 1 positions hold the i + 1 smallest values of the whole array, in order. To extend the prefix by one, you only need the minimum of the remaining suffix arr[i..n-1], and a linear scan finds it. Swapping that minimum into position i keeps the invariant true, and after n - 1 iterations the last element is automatically the largest.
What makes selection sort distinctive is that the amount of work never depends on the input. Even if the array is already sorted, every pass still scans the entire suffix to confirm which element is smallest, so there is no early exit like the one bubble sort has. On the other hand, it performs at most n - 1 swaps, one per pass, and the reference code skips the swap entirely when the minimum is already in place. That makes it attractive in the rare case where writes are far more expensive than reads.
Approach: In-place selection of the minimum
- Store the array length in
n. - Loop
ifrom 0 ton - 2. Positioniis the slot to fill with the next smallest value. - Assume the minimum of the unsorted suffix is at
minIdx = i. - Scan
jfromi + 1ton - 1, and wheneverarr[j] < arr[minIdx], updateminIdx = j. - If
minIdxdiffers fromi, swaparr[i]witharr[minIdx]so the minimum joins the sorted prefix. - Return
arronce every position up ton - 2has been filled.
Step-by-step example
arr = [64, 25, 12, 22, 11]
- i = 0: scanning indices 1 to 4 finds the minimum 11 at index 4. Swap with index 0 to get [11, 25, 12, 22, 64].
- i = 1: the minimum of [25, 12, 22, 64] is 12 at index 2. Swap to get [11, 12, 25, 22, 64].
- i = 2: the minimum of [25, 22, 64] is 22 at index 3. Swap to get [11, 12, 22, 25, 64].
- i = 3: the minimum of [25, 64] is 25, already at index 3, so
minIdx == iand no swap happens. - The loop ends and the function returns [11, 12, 22, 25, 64].
Code: Python, Java, C++
1class Solution:
2 def selectionSort(self, arr: List[int]) -> List[int]:
3 n = len(arr)
4 for i in range(n - 1):
5 minIdx = i
6 for j in range(i + 1, n):
7 if arr[j] < arr[minIdx]:
8 minIdx = j
9 if minIdx != i:
10 arr[i], arr[minIdx] = arr[minIdx], arr[i]
11 return arr1class Solution {
2 public int[] selectionSort(int[] arr) {
3 int n = arr.length;
4 for (int i = 0; i < n - 1; i++) {
5 int minIdx = i;
6 for (int j = i + 1; j < n; j++) {
7 if (arr[j] < arr[minIdx]) {
8 minIdx = j;
9 }
10 }
11 if (minIdx != i) {
12 int temp = arr[i];
13 arr[i] = arr[minIdx];
14 arr[minIdx] = temp;
15 }
16 }
17 return arr;
18 }
19}1class Solution {
2public:
3 vector<int> selectionSort(vector<int>& arr) {
4 int n = arr.size();
5 for (int i = 0; i < n - 1; i++) {
6 int minIdx = i;
7 for (int j = i + 1; j < n; j++) {
8 if (arr[j] < arr[minIdx]) {
9 minIdx = j;
10 }
11 }
12 if (minIdx != i) {
13 swap(arr[i], arr[minIdx]);
14 }
15 }
16 return arr;
17 }
18};Time and space complexity
O(n²)
Iteration i scans n - 1 - i elements, so the total number of comparisons is (n - 1) + (n - 2) + down to 1, which equals n(n - 1)/2. That count is the same for sorted, reversed and random input, so best, average and worst cases are all O(n²).
O(1)
Only the indices i, j and minIdx are stored. The array is rearranged in place without any auxiliary buffer.
Other approaches
Insertion sort (time O(n²), space O(1))
Builds the sorted prefix by inserting each new element into position rather than selecting the global minimum. It has the same worst case but runs in O(n) on nearly sorted data, so it is usually the better simple sort.
Heap sort (time O(n log n), space O(1))
Selection sort with a smarter way to find the extreme value. A binary heap returns the maximum in O(log n), so the n selections cost O(n log n) total while still sorting in place.
Common mistakes
- Swapping every time a smaller element is found during the scan instead of once at the end. That still sorts, but it turns the algorithm into a clumsy exchange sort with up to O(n²) swaps and loses selection sort's main advantage.
- Starting the inner loop at
iinstead ofi + 1. It does no harm to correctness but comparesarr[i]with itself every pass. - Assuming selection sort is stable. Swapping the minimum into position
ican jump an element over an equal value, so for [2a, 2b, 1] the result is [1, 2b, 2a]. - Running the outer loop to
n - 1inclusive. The final element has nothing left to compare against, so the loop should stop atn - 2.
Frequently asked questions
Why is selection sort O(n²) even on a sorted array?
Each pass has to look at every remaining element to be sure it found the minimum, and nothing in the algorithm notices that the data is already in order. The comparison count is always n(n - 1)/2.
Is selection sort stable?
No, not in the standard swap-based form shown here. The long-distance swap can reorder equal keys. A stable variant exists that shifts elements instead of swapping, but it costs more writes.
What is the difference between selection sort and bubble sort?
Both are O(n²), but selection sort does at most n - 1 swaps while bubble sort can do O(n²) swaps. Bubble sort with an early exit can finish in O(n) on sorted input, which selection sort cannot.
When would you actually use selection sort?
Mostly for teaching, or for tiny arrays where writes are expensive, such as some flash memory scenarios. Its minimal number of swaps is its one real strength.