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
- Always n(n − 1)/2 comparisons, whatever the input
- At most n − 1 swaps
- Not stable as usually written
Edge cases to test
- Already sorted: still n(n − 1)/2 comparisons
- All equal
- One element
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 numsC++
#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
- Bubble Sort (Easy)
- Insertion Sort (Easy)
- Merge Sort (Medium)
- Quick Sort (Lomuto) (Medium)
- Quick Sort (Hoare) (Medium)
- Counting Sort (Easy)
- Radix Sort (LSD) (Medium)
- Bucket Sort (Medium)
- Kth Largest Element (Quickselect) (Medium)
- Count Inversions (Hard)
- Largest Number (Medium)