Insertion sort

JavaScript, Algorithm, Array · Dec 28, 2020

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

const insertionSort = arr =>
  arr.reduce((acc, x) => {
    if (!acc.length) return [x];
    acc.some((y, j) => {
      if (x <= y) {
        acc.splice(j, 0, x);
        return true;
      }
      if (x > y && j === acc.length - 1) {
        acc.splice(j + 1, 0, x);
        return true;
      }
      return false;
    });
    return acc;
  }, []);
insertionSort([6, 3, 4, 1]); // [1, 3, 4, 6]

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 · 210 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