Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Implementation

Program gif introduces the BucketSorter class. The BucketSorter class extends the AbstractSorter class defined in Program gif. This bucker sorter is designed to sort specifically an array of Ints. The BucketSorter class contains two fields, m and count. The integer m simply keeps track of the size of the universe. The count variable is an array of integers used to count the number of occurrences of each element of the universal set.

   program45035
Program: BucketSorter class constructor and sort methods.

The constructor for the BucketSorter class takes a single argument which specifies the size of the universal set. The variable m is set to the specified value, and the count array is initialized to have the required size.

Program gif defines the no-arg sort method. It casts the array to an array Ints and calls the sort(Int[]) method defined in Program gif.

The sort(Int[]) method defined in Program gif sorts an array of Ints. It begins by setting all of the counters to zero (lines 9-10). This can clearly be done in O(m) time.

   program45058
Program: BucketSorter class sort method.

Next, a single pass is made through the data to count the number of occurrences of each element of the universe (lines 11-12). Since each element of the array is examined exactly once, the running time is O(n).

In the final step, the sorted output sequence is created (lines 13-15). Since the output sequence contains exactly n items, the body of the inner loop (line 15) is executed exactly n times. During the tex2html_wrap_inline57340 iteration of the outer loop (line 13), the loop termination test of the inner loop (line 14) is evaluated tex2html_wrap_inline69301 times. As a result, the total running time of the final step is O(m+n).

Thus, the running time of the bucket sort method is O(m+n). Note that if m=O(n), the running time for bucket sort is O(n). That is, the bucket sort algorithm is a linear-time sorting algorithm! Bucket sort breaks the tex2html_wrap_inline59646 bound associated with sorting algorithms that use binary comparisons because bucket sort does not do any binary comparisons. The cost associated with breaking the tex2html_wrap_inline59646 running time bound is the O(m) space required for the array of counters. Consequently, bucket sort is practical only for small m. For example, to sort 16-bit integers using bucket sort requires the use of an array of tex2html_wrap_inline69319 counters.


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.