Skip to content

Instantly share code, notes, and snippets.

@paulohfev
Last active April 8, 2025 14:26
Show Gist options
  • Select an option

  • Save paulohfev/b932ea1ecb4d8d7b7cee2bf494fe72d2 to your computer and use it in GitHub Desktop.

Select an option

Save paulohfev/b932ea1ecb4d8d7b7cee2bf494fe72d2 to your computer and use it in GitHub Desktop.
Selection sort algorithm
// 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