Last active
April 11, 2021 18:55
-
-
Save inodaf/18231d9d1efb51fa3cdb7807ed80f36f to your computer and use it in GitHub Desktop.
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
function getIndexOfMin(list: number[]) { | |
let current = list[0]; | |
let index = 0; | |
for (let i = 0; i < list.length; i++) { | |
if (list[i] < current) { | |
current = list[i]; | |
index = i; | |
} | |
} | |
return index; | |
} | |
// O(n^2) | |
function selectionSort(list: number[]) { | |
const sorted = []; | |
const originalLength = [...list].length; | |
for (let i = 0; i < originalLength; i++) { | |
const index = getIndexOfMin(list); | |
sorted.push(list.splice(index, 1).shift()); | |
} | |
return sorted; | |
} | |
selectionSort([5, 4, 3, 7, 6, -1, 0, 15]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment