Last active
March 17, 2018 18:11
-
-
Save mdmen/af93fd6fd618c26895ab4f2d25494bbd to your computer and use it in GitHub Desktop.
Selection sort in ES6
This file contains 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
/** | |
* 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