

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


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 how many buckets to initialize. Secondly, we must be able to create enough buckets in memory for every element that we might possibly encounter in the unsorted array. It may be impossible to declare an array large enough to fulfill this requirement on some systems. Accordingly, we should augment our function above to determine whether the array was properly allocated at runtime. This can be achieved by inserting the following line after the calloc() statement: if (bucket == NULL) return; Thus, we see a tradeoff between time and space complexity here. The O(n) bucket sort outpe rforms any comparison based sort (in terms of its BigO h notation, at least), but places a much higher demand on system memory than any of the other sorting algorithms we have seen so far. The reader should be aware that there are other variations of bucket sort that rely on buckets that accommodate small ranges of elements, rather than single values. A discussion of that sort of implementation is available on Wikipedia (http://en.wikipedia.org/wiki/Bucket_sort). The notes presented here are loosely based on information from that page.
The idea behind radix sort is slightly more complex than that of bucket sort, although not terribly so. The algorithm proceeds as follows: