Selection Sort

Pattern: Basic sorts

easy

Sort by repeatedly finding the smallest remaining element and swapping it into the next position.

The problem

You are given an array of between 1 and 1500 whole numbers. Sort it in increasing order using selection sort, and return it. For example, [5, 2, 9, 1] becomes [1, 2, 5, 9].

On the original site the problem is written a little differently, so use the link above for its exact wording. The function name selectionSort and the limits are this guide's own.

Think first

  • Which value must end up at index 0? How do you find it?
  • Once index 0 is correct, what is left to sort?
  • How many swaps does selection sort make in total, at most?

Hints

    Brute force, and why it fails

    The built-in sort is the practical answer, and this problem asks you to write the algorithm yourself. Selection sort is itself the "obvious" sort: always O(n²) comparisons, even on sorted input, but at most n - 1 swaps. That small number of writes is its one advantage, for example when writing to memory is expensive.

    The key insight

    Grow a sorted part at the front. After round i, the first i + 1 positions hold the smallest values in order and never change again. Each round only has to find the minimum of what is left.

    Dry run

    50i
    21 
    92 
    13 
    i0

    nums = [5, 2, 9, 1]. Position 0 needs the smallest of the whole array. Scan all four values.

    Step 1 of 5

    The plan

    n = length(nums)
    for i from 0 to n - 2:
        smallest = i
        for j from i + 1 to n - 1:          # find the smallest in nums[i..n-1]
            if nums[j] < nums[smallest]:
                smallest = j
        swap nums[i] and nums[smallest]     # it belongs at position i
    return nums
    

    Complexity

    Time
    O(n²)
    Space
    O(1)

    About n²/2 comparisons whatever the input, and at most n - 1 swaps. The sort works inside the array.

    Edge cases

    • One element: the outer loop does not run.
    • Already sorted: still O(n²) comparisons, but every swap is with itself.
    • Duplicates: equal values may change their relative order, so selection sort is not stable.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] selectionSort(int[] nums) {
            int n = nums.length;
            for (int i = 0; i < n - 1; i++) {
                int smallest = i;                       // find the smallest in nums[i..n-1]
                for (int j = i + 1; j < n; j++) {
                    if (nums[j] < nums[smallest]) {
                        smallest = j;
                    }
                }
                int temp = nums[i];                     // put it at position i
                nums[i] = nums[smallest];
                nums[smallest] = temp;
            }
            return nums;
        }
    }

    C++

    class Solution {
    public:
        vector<int> selectionSort(vector<int>& nums) {
            int n = static_cast<int>(nums.size());
            for (int i = 0; i < n - 1; i++) {
                int smallest = i;                       // find the smallest in nums[i..n-1]
                for (int j = i + 1; j < n; j++) {
                    if (nums[j] < nums[smallest]) {
                        smallest = j;
                    }
                }
                swap(nums[i], nums[smallest]);          // put it at position i
            }
            return nums;
        }
    };

    Python

    class Solution:
        def selectionSort(self, nums):
            n = len(nums)
            for i in range(n - 1):
                smallest = i                            # find the smallest in nums[i..n-1]
                for j in range(i + 1, n):
                    if nums[j] < nums[smallest]:
                        smallest = j
                nums[i], nums[smallest] = nums[smallest], nums[i]   # put it at position i
            return nums

    Common mistakes

    • Swapping every time a smaller value is seen, instead of once per round. That still sorts, but it is really a slower bubble sort.
    • Remembering the smallest value but not its index, so the swap has nowhere to go.
    • Starting the inner loop at j = 0 instead of i + 1, which disturbs the finished part.

    Similar problems