Selection sort

JavaScript, Algorithm, Array · Oct 13, 2021

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. 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]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • JavaScript Arrays

    Master array manipulation in JavaScript with this ES6 snippet collection.

    Collection · 207 snippets

  • Heap sort

    Sorts an array of numbers, using the heapsort algorithm.

    JavaScript, Algorithm · Dec 28, 2020

  • Bucket sort

    Sorts an array of numbers, using the bucket sort algorithm.

    JavaScript, Algorithm · Dec 29, 2020

  • Quick sort

    Sorts an array of numbers, using the quicksort algorithm.

    JavaScript, Algorithm · Oct 13, 2021