Bucket Sort
The idea behind bucket sort is that if we know the range of our elements to be sorted, we can set up
buckets for each possible element, and just toss elements into their corresponding buckets. We then
empty the buckets in order, and the result is a sorted list.
In implementing this algorithm, we can easily use an array to represent our buckets, where the value at
each array index will represent the number of elements in the corresponding bucket. If we have integers
on the range
[0..max]
, then we set up an array of
(max + 1)
integers and initialize all the values to
zero. We then proceed sequentially through the unsorted array, reading the value of each element, going
to the corresponding index in the buckets array, and incrementing the value there.
Then our function, in C, is as follows:
void bucketsort(int array[], int n, int max) {
int i, j = 0;
/* Declare an array of size (max + 1) and initialize all values to zero. */
int *bucket = calloc(max + 1, sizeof(int));
/* Place each element from the unsorted array into its corresponding bucket. */
for (i = 0; i < n; i++)
bucket[array[i]]++;
/* Sequentially empty each bucket back into the original array. */
for (i = 0; i < max; i++)
while(bucket[i]--)
array[j++] = i;
}
We immediately see two drawbacks to this sorting algorithm. Firstly, we must know the maximum
value of any element that can be found in the unsorted array. Without this information, we do know
This
preview
has intentionally blurred sections.
Sign up to view the full version.

This is the end of the preview.
Sign up
to
access the rest of the document.
- Summer '09
- Computer Science, Sort, bucket sort
-
Click to edit the document details