Bucket sort

JavaScript, Algorithm, Array · Dec 29, 2020

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

const bucketSort = (arr, size = 5) => {
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const buckets = Array.from(
    { length: Math.floor((max - min) / size) + 1 },
    () => []
  );
  arr.forEach(val => {
    buckets[Math.floor((val - min) / size)].push(val);
  });
  return buckets.reduce((acc, b) => [...acc, ...b.sort((a, b) => a - b)], []);
};
bucketSort([6, 3, 4, 1]); // [1, 3, 4, 6]

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

  • Quick sort

    Sorts an array of numbers, using the quicksort algorithm.

    JavaScript, Algorithm · Oct 13, 2021

  • Selection sort

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

    JavaScript, Algorithm · Oct 13, 2021