Files
30-seconds-of-code/snippets/selectionSort.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

864 B

title, tags, firstSeen, lastUpdated
title tags firstSeen lastUpdated
selectionSort algorithm,array,intermediate 2020-12-27T22:22:44+02:00 2020-12-29T13:04:24+02:00

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;
};
selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]