Skip to content

Instantly share code, notes, and snippets.

@inodaf
Last active April 11, 2021 18:55
Show Gist options
  • Save inodaf/18231d9d1efb51fa3cdb7807ed80f36f to your computer and use it in GitHub Desktop.
Save inodaf/18231d9d1efb51fa3cdb7807ed80f36f to your computer and use it in GitHub Desktop.
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