What is Selection Sort and How to Implement it in JavaScript
Selection sort is a sorting algorithm that sorts by repeatedly finding the minimum element of the unsorted array then placing that element at the beginning. Every loop the algorithm advances the array index so the lowest element will be added next to the previous lowest element. This repeats until the entire input is sorted.
Selection sort has a time complexity of O(n^2) due to the two nested loops. This is one of the slowest sorting algorithms and has little practical use.
Step-By-Step Example
First Pass
unsorted index = 0;
(2, 9, 1, 4, 8) => (1,2, 9, 4, 8)
1 is the lowest so it is moved to the beginning of the unsorted index.
Second Pass
unsorted index = 1;
(1, 2, 9, 4, 8) => (1, 2, 9, 4, 8)
No change as the 2nd lowest element is in the correct place.
Third Pass
unsorted index = 2;
(1, 2, 9, 4, 8) => (1, 2, 4, 9, 8)
4 is the lowest so it is moved to the beginning of the unsorted index.
Forth Pass
unsorted index = 3;
(1, 2, 4, 9, 8) => (1, 2, 4, 8, 9)
8 is the lowest so it is moved to the beginning of the unsorted index.
Fifth Pass
unsorted index = 4;
(1, 2, 4, 8, 9) => (1, 2, 4, 8, 9)
Implementation
1const startingArray = [2, 9, 1, 4, 8]23function selectionSort(arr) {4 let unsortedArr = [...arr]5 let sortedArr = []6 let arrSize = unsortedArr.length7 let n = 089 // loop once for every item in the starting array10 while (n < arrSize) {11 let minimum = unsortedArr[0]12 let index1314 // loop through unsorted array and find minimum15 for (let i = 0; i < arrSize; i++) {16 if (unsortedArr[i] < minimum) {17 minimum = unsortedArr[i]18 index = i19 }20 }2122 // push minimum value to sorted array23 sortedArr.push(minimum)2425 // remove minimum value from unsorted array26 unsortedArr.splice(index, 1)2728 // advance the outer counter29 n++30 }3132 return sortedArr33}3435selectionSort(startingArray) // [1, 2, 4, 8, 9]
Selection sort is more efficient than bubble sort in that the number of swaps will never be more than 0(n), however it shares the same time complexity as bubble sort O(n^2) so it is too slow to use for anything practical.
Cheers!
Find a mistake? Help me fix it by submitting a pull request.
← back to all posts