Searching & Sorting
Selection Sort
Algorithm · Starter
Level: StarterSort First
Watch it run
5
2
8
1
9
3
Step 1 of 25
Selection sort: find the smallest value in the unsorted part and put it at the front.
Complexity
| Name | Best | Average | Worst | Memory | Stable | Comments |
|---|---|---|---|---|---|---|
| Selection sort | n2 | n2 | n2 | 1 | No |
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.
Code
import Sort from '../Sort';
export default class SelectionSort extends Sort {
sort(originalArray) {
// Clone original array to prevent its modification.
const array = [...originalArray];
for (let i = 0; i < array.length - 1; i += 1) {
let minIndex = i;
// Call visiting callback.
this.callbacks.visitingCallback(array[i]);
// Find minimum element in the rest of array.
for (let j = i + 1; j < array.length; j += 1) {
// Call visiting callback.
this.callbacks.visitingCallback(array[j]);
if (this.comparator.lessThan(array[j], array[minIndex])) {
minIndex = j;
}
}
// If new minimum element has been found then swap it with current i-th element.
if (minIndex !== i) {
[array[i], array[minIndex]] = [array[minIndex], array[i]];
}
}
return array;
}
}References
Practice
Sort First
- Contains DuplicateEasy
- Valid AnagramEasy
- Meeting RoomsEasy
- Merge Sorted ArrayEasy
- Sort ColorsMedium
- Largest NumberMedium
- H-IndexMedium
- Wiggle Sort IIMedium
- Sort an ArrayMedium
- Custom Sort StringMedium
- Insertion Sort ListMedium
- Maximum GapHard
- Count of Smaller Numbers After SelfHard
Spotted a mistake or something unclear? Report it on GitHub.