Skip to content

Instantly share code, notes, and snippets.

@mdmen
Last active March 17, 2018 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdmen/af93fd6fd618c26895ab4f2d25494bbd to your computer and use it in GitHub Desktop.
Save mdmen/af93fd6fd618c26895ab4f2d25494bbd to your computer and use it in GitHub Desktop.
Selection sort in ES6
/**
* Find the index of the smallest element of the array
* @param {array} list - Array of numbers
* @returns {number} - Index
*/
const findMinItemIndex = list => {
let minIndex = 0;
let minItem = list[0];
const length = list.length;
for (let i = 1; i < length; i++) {
if (list[i] < minItem) {
minIndex = i;
minItem = list[i];
}
}
return minIndex;
};
/**
* Selection sort
* @param {array} list - Array of numbers
* @returns {array} - Sorted array
*/
const selectionSort = list => {
const newList = [];
const length = list.length;
for (let i = 0; i < length; i++) {
const minIndex = findMinItemIndex(list);
newList.push(list.splice(minIndex, 1)[0]);
}
return newList;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment