Skip to content

Instantly share code, notes, and snippets.

@yavgel85
Created March 26, 2021 11:53
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 yavgel85/5be66c2a236936c2212a3befb8b32799 to your computer and use it in GitHub Desktop.
Save yavgel85/5be66c2a236936c2212a3befb8b32799 to your computer and use it in GitHub Desktop.
selectionSort #js #algorithm
// Sorts an array of numbers, using the selection sort algorithm.
// Use the spread operator (...) to clone the original array, arr.
// Use a for loop to iterate over elements in the array.
// Use Array.prototype.slice() and Array.prototype.reduce() to find the index of the minimum element in the subarray to the right of the current index and perform a swap, if necessary.
const selectionSort = arr => {
const a = [...arr];
for (let i = 0; i < a.length; i++) {
const min = a
.slice(i + 1)
.reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
if (min !== i) [a[i], a[min]] = [a[min], a[i]];
}
return a;
};
// Examples
selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment