Bucket Sort:
Scenario:
Work when keys are in a small range.
Linked List.
Algorithm(Stable):
1. Walk through each item and enqueue each item into its appropriate queue.
2. Concatenate queues in order
Complexity:
O(queue+n):
O(q) time to initialize and concatenate buckets together.
O(n) time to put items to buckets.
Counting Sort:
Scenario:
Array. When items are keys, no associated values.
Algorithm: (Stable, Similar to bucket sort)
Count copies of each key.
Complexity:
O(queue+n)
For objects, counting sort with complete items for key plus associated item.
for(i=0;i<x.length;i++)
{
counts[x[i].key]++;
}
//Then, do a scan so counts[i] contains # of keys less than i.
total = 0;
for(j=0;j<counts.length;j++)
{
c=counts[j];
counts[j] = total;
total += c;
}
//let y be output array, counts[i] tells us first index of y to put items with key i.
for(i=0;i<x.length;i++)
{
y[counts[x[i].key]++]=x[i];
}
Radix Sort(Base Sort):
sort 1000 items in range 0~99,999,999
Algorithm:
Sort on last digit, then recursively on second digit, up to the most significant digit.
Works because bucket&counting sort are stable.
Faster if we sort on 2 digits at a time(choose radix/base q = 100). For computers, more natural to choose power-of-two radix like q=256
Complexity:
each pass inspects log2(q) bits of each key.
if all keys represented in b bits, # of passes is ceiling of b/log2(q)
O((n+q)*ceil(b/log2(q))