Today's Material: - Lower Bounds On Comparison-Based Sorting - Linear-Time Sorting Algorithms
Today's Material: - Lower Bounds On Comparison-Based Sorting - Linear-Time Sorting Algorithms
1
How Fast Can We Sort?
• Basic Sorting Algorithms
– BubleSort, InsertionSort and SelectionSort all run
in O(N^2)
a < b a > b
a<b<c b<c<a
Remaining
c<a<b b<a<c
Orderings
a<c<b c<b<a
a < c a > c b < c b > c
7
Example (NlogN) Problems
• Convex Hull
– Given a set of points in the plane, find the closest
convex polygon that encloses them
• Closest Pair
– Given a list of n elements, which pair are closest in
value
• Element Uniqueness
– Given a list of n numbers, are there any duplicates
in the list
8
What about Counting Sort?
• Problem: Sort integers in the range 1 to B
• Algorithm:
1. Allocate an array Count having B slots (“buckets”)
2. Initialize: Count[i] = 0 for i = 1 to B
3. Given input integer i, Count[i]++
4. After reading all inputs, scan Count[i] for i = 1 to B
and print i if Count[i] is non-zero
1 2 3 4 1 2 3 4 5
2 2 4 5 3
B
v
2 2 3 5
B 1 3
s v
1 2 3 5
B 1 3 3
s r v
1 2 2 5
B 1 3 3 4
s r v e
1 2 2 4
B 1 1 3 3 4
0 2 2 4 a s r v e 11
Counting Sort Running Time
• What is the running time for sorting N
integers using bucket sort?
– Running Time: O(B+N)
– B to zero/scan the array and N to read the input
– If B is O(N), then running time for Bucket sort =
O(N)
– Doesn’t this violate the (N log N) lower bound
result?
14
Radix Sort Running Time
• P = # of digits iterations over the data set
15
Summary of Sorting
• Sorting choices:
– O(N2) – Bubblesort, Selection Sort, Insertion Sort
– O(Nx) – Shellsort (x = 3/2, 4/3, 2, etc. depending on
incr. seq.)
– O(N log N) average case running time:
• Mergesort: easy to code but uses O(N) extra space
• Heapsort: needs 2 comparisons to move data (between 2
children and parent) – may not be fast in practice
• Quicksort: fastest in practice but trickier to code, O(N2)
worst case
– O(P·N)
• Radix sort (using Counting sort) for special cases where
keys are P digit integers/strings
16