Sorting / Beginner
Selection Sort Visualizer
Find the smallest value in the unsorted part and swap it to the front. Repeat until nothing is left.
Start the Selection Sort simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(n²) |
|---|---|
| Average time | O(n²) |
| Worst time | O(n²) |
| Extra space | O(1) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- Selection sort on 5 values.
[5, 1, 4, 2, 8] - Start of pass 1: assume 5 at index 0 is the smallest.
- Is 1 smaller than the current minimum 5?
- Yes. The new minimum is 1.
- Is 4 smaller than the current minimum 1?
- Is 2 smaller than the current minimum 1?
- Is 8 smaller than the current minimum 1?
- Swap the minimum 1 into index 0.
[1, 5, 4, 2, 8] - Start of pass 2: assume 5 at index 1 is the smallest.
- Is 4 smaller than the current minimum 5?
- Yes. The new minimum is 4.
- Is 2 smaller than the current minimum 4?
- Yes. The new minimum is 2.
- Is 8 smaller than the current minimum 2?
- Swap the minimum 2 into index 1.
[1, 2, 4, 5, 8] - Start of pass 3: assume 4 at index 2 is the smallest.
- Is 5 smaller than the current minimum 4?
- Is 8 smaller than the current minimum 4?
- 4 is already the smallest. No swap needed.
- Start of pass 4: assume 5 at index 3 is the smallest.
- Is 8 smaller than the current minimum 5?
- 5 is already the smallest. No swap needed.
- Sorted. 10 comparisons and 2 swaps.
Selection sort in Java, Python, C++, C and JavaScript
void selectionSort(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
swap(a, i, min);
}
}
def selection_sort(a):
for i in range(len(a) - 1):
min_i = i
for j in range(i + 1, len(a)):
if a[j] < a[min_i]:
min_i = j
a[i], a[min_i] = a[min_i], a[i]
void selectionSort(vector<int>& a) {
int n = a.size();
for (int i = 0; i < n - 1; i++) {
int mn = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[mn]) {
mn = j;
}
}
swap(a[i], a[mn]);
}
}
void selectionSort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
int mn = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[mn]) {
mn = j;
}
}
int t = a[i]; a[i] = a[mn]; a[mn] = t;
}
}
function selectionSort(a) {
for (let i = 0; i < a.length - 1; i++) {
let min = i;
for (let j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
[a[i], a[min]] = [a[min], a[i]];
}
}In an interview
It makes at most n − 1 swaps, which matters when writing to memory is expensive. It is not stable.