Algo-Sim › Sorting & Divide and Conquer

Selection Sort

Easy · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input

For each position, scan the rest for the minimum and swap it in. Always n(n − 1)/2 comparisons, but only n − 1 swaps.

Problem

Sort nums into ascending order with selection sort: for each position from the left, find the smallest value in the unsorted part and swap it into that position.

Constraints

Edge cases to test

Follow-up questions

When does it make sense?
When writes are expensive: it does at most n − 1 swaps.
Is it stable?
Not as usually written: a swap can jump an element past an equal one. Shifting instead of swapping makes it stable.

Solution

Java

public int[] selectionSort(int[] nums) {
    for (int i = 0; i < nums.length - 1; i++) {
        int smallest = i;
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] < nums[smallest]) smallest = j;
        }
        int t = nums[i]; nums[i] = nums[smallest]; nums[smallest] = t;
    }
    return nums;
}

Python

def selection_sort(nums):
    for i in range(len(nums) - 1):
        smallest = i
        for j in range(i + 1, len(nums)):
            if nums[j] < nums[smallest]:
                smallest = j
        nums[i], nums[smallest] = nums[smallest], nums[i]
    return nums

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> selectionSort(vector<int> &nums) {
        for (int i = 0; i < int(nums.size()) - 1; i++) {
            int smallest = i;
            for (int j = i + 1; j < int(nums.size()); j++) {
                if (nums[j] < nums[smallest])
                    smallest = j;
            }
            int t = nums[i];
            nums[i] = nums[smallest];
            nums[smallest] = t;
        }
        return nums;
    }
};

More Sorting & Divide and Conquer problems