Lably
Skip to content

Bucket sort

Sorting algorithm

  • 7 min read
  • 5 chapters

Related on Lably

Through Floor and ceiling functions, Insertion sort and Quicksort

Bucket sort works as follows:

  1. Set up an array of initially empty "buckets".
  2. Scatter: Go over the original array, putting each object in its bucket.
  3. Sort each non-empty bucket.
  4. Gather: Visit the buckets in order and put all elements back into the original array.

Pseudocode

<b id="mwIg">function</b> bucketSort(array, k) <b id="mwIw">is</b> buckets ← new array of k empty lists M ← 1 + the maximum key value in the array <b id="mwJA">for</b> i = 0 <b id="mwJQ">to</b> length(array) <b id="mwJg">do</b> insert <i id="mwJw">array[i]</i> into <i id="mwKA">buckets[floor(k × array[i] / M)]</i> <b id="mwKQ">for</b> i = 0 <b id="mwKg">to</b> k <b id="mwKw">do</b> nextSort(buckets[i]) <b id="mwLA">return</b> the concatenation of buckets[0], ...., buckets[k]

Let array denote the array to be sorted and k denote the number of buckets to use. One can compute the maximum key value in linear time by iterating over all the keys once. The floor function must be used to convert a floating number to an integer ( and possibly casting of datatypes too ). The function nextSort is a sorting function used to sort each bucket. Conventionally, insertion sort is used due to its relatively high performance with small numbers of elements, but other algorithms could be used as well, such as selection sort or merge sort. Using bucketSort itself as nextSort produces a relative of radix sort; in particular, the case n = 2 corresponds to quicksort (although potentially with poor pivot choices).

Sign in to keep reading

4 more chapters are free with a Lably account.

More in Computing and communication