Bucket Sort Algorithm In Javascript

Bucket (bin) sort is a sorting algorithm that parts an array into buckets. Each of these are sorted recursively with the bucket sorting algorithm. The basic procedure of Bucket Sort is:

  1. Create an empty array
  2. Loop through the original array and put each object in a “bucket”
  3. Sort each of the non-empty buckets
  4. Check the buckets in order and then put all objects back into the original array
var array = [2, 4, 1, 5, 3];
bucketSort(array);

function bucketSort(a) {
  var r = [], b = [], v, c;
  for (v of a) (b[v] || (b[v] = [])).push(v);
  for (c of b) if (c != null) for each (v in c) r.push(v);
  return r;
}

For more information on the Bucket Sort check the Wikipedia page here: Bucket Sort - Wikipedia.org.

Written on September 10, 2013