SortingInLinearTime
SortingInLinearTime
Sorting
• Sort n integers in
• Merge Sort, Heap Sort in the worst case
• Quick Sort on average
• Runs in
C
2 0 2 3 0 1
Counting Sort
A
2 5 3 0 2 3 0 3
C (old)
2 0 2 3 0 1
C(current state)
2 2 4 7 7 8
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
2 2 4 7 7 8
B
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
2 2 4 7 7 8
B
3
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
2 2 4 6 7 8
B
3
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
2 2 4 6 7 8
B
0 3
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
1 2 4 6 7 8
B
0 3
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
1 2 4 6 7 8
B
0 3 3
Counting Sort
A
2 5 3 0 2 3 0 3
C(current state)
0 2 2 4 7 7
B
0 0 2 2 3 3 3 5
Counting Sort
• Counting sort is stable
• Elements with the same value appear in the output array in
the same order as they do in the input array.
Radix Sort
• We can sort the elements
• By most significant (leftmost) digit
• Then sort the resulting bins recursively
• Finally combine the bins in order.
• Generates many intermediate bins to track
Radix Sort
• Let’s start by the least significant bit
• For example,
Radix Sort