3.4. Distribution-based Sort
Bucket sort, radix sort.
Unlike comparison-based algorithms in Sections 3.2 and 3.3, distribution-based sorting algorithms do not make comparisons between keys in the input array; instead, they distribute keys into ordered buckets and merge keys in the buckets.
Bucket Sort
Let us create an abstract class, AbstractBucketSort
inheriting AbstractSort
:
L2
: declares a list of buckets where each bucket is represented by aDeque
.L6
: does not pass any comparator toAbstractSort
since no comparison is needed.L7
: creates a pre-defined number of buckets.
What kind of input keys can work with distribution-based sorting algorithms?
We then define a helper method sort()
:
L7
:bucketIndex
is a function that takes a comparable key and returns the appropriate bucket index of the key.L9-10
: adds the keys within the range in the input array to the buckets.L13-16
: puts all keys in the buckets back to the input array while keeping the order.
How many assignments are made by the
sort()
method inBucketSort
?
Integer Bucket Sort
Let us create the IntegerBucketSort
class inheriting BucketSort
that sorts integers within a specific range in ascending order:
L2
: takes the smallest integer in the range.L8
: passes the number of buckets,max - min
, to be initialized to the super constructor.\
We then override the sort()
method:
L3
: passes a lambda expression that takeskey
and returnskey - MIN
indicating the index of the bucket thatkey
should be assigned to.
Is it possible to implement
DoubleBucketSort
that can handle double instead of integer keys?
Radix Sort
Let us create an abstract class, RadixSort
, inheriting BucketSort<Integer>
:
L3
: creates10
buckets to sort any range of integers.L6
: returns the order of the most significant digit in the input array.
LSD Radix Sort
Let us create the LSDRadixSort
class inheriting RadixSort
that sorts the integer keys from the least significant digit (LSD) to the most significant digit (MSD):
L5
: iterates from LSD to MSD.
Benchmarks
The followings compare runtime speeds between advanced sorting algorithms where the input arrays consist of random integer keys:
Last updated