Created
December 19, 2022 16:15
-
-
Save MohdSaifulM/666acd0b37926f9a4b20cd96480a8ba7 to your computer and use it in GitHub Desktop.
Algorithms - Sorting (Selection Sort)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Selection sort | |
- Time complexity O(n^2) | |
- Best use case if we want to limit the swapping of elements | |
*/ | |
function selectionSort(arr) { | |
for (let i = 0; i < arr.length; i++) { | |
// Store first element as the smallest value | |
let minIndex = i; | |
// Compare this to the next item in the array until we find the smallest in the array | |
for (let j = i + 1; j < arr.length; j++) { | |
// If smaller number is found, store new minIndex | |
if (arr[j] < arr[minIndex]) minIndex = j; | |
} | |
// If the new minimum is not the value of the index we begin with swap the two indexes | |
if (i !== minIndex) [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]] | |
} | |
return arr; | |
} | |
selectionSort([3, 23, 67, 2, 5, 76, 54, 90, 102, 4, 7, 32, 13]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment