Last active
April 8, 2025 14:26
-
-
Save paulohfev/b932ea1ecb4d8d7b7cee2bf494fe72d2 to your computer and use it in GitHub Desktop.
Selection sort algorithm
This file contains hidden or 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 | |
| const sort = (arr) => { | |
| let list = arr | |
| const findSmallestValue = () => { | |
| let smallest = list[0] | |
| let smallestIndex = 0 | |
| for (let i = 1; i < list.length; i++) { | |
| if (list[i] < smallest) { | |
| smallest = list[i] | |
| smallestIndex = i | |
| } | |
| } | |
| return smallestIndex | |
| } | |
| const sortedList = [] | |
| const originalLength = list.length | |
| for (let i = 0; i < originalLength; i++) { | |
| let smallestValueIndex = findSmallestValue() | |
| sortedList.push(list[smallestValueIndex]) | |
| list = list.toSpliced(smallestValueIndex, 1) | |
| } | |
| return sortedList | |
| } | |
| console.log(sort([5, 3, 6, 2, 10])) // Output: [2, 3, 5, 6, 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment