Minimum and Maximum
Minimum and Maximum
Approach 1
•Sort n/2 pairs. Find min of losers, max of winners.
# comparisons: n/2 + n/2 –1 + n/2-1 = 3n/2 –2.
Is this the best possible?
Approach 2
•Divide into n/2 pairs. Compare the first pair, set winner to
current max, loser to current min.
•Sort next pair, compare winner to current max, loser to
current min.
#comparisons: 1 + 3(n/2 –1) = 3n/2 –2.
Lower bounds for the MIN and MAX
“Proof” from the web: For each comparison, x<y, score a point
if this is first comparison that x loses or if y wins and 2
points if both occur. Before the algorithm can terminate n-2
must both win and lose (since they aren't min or max) and 2
elements must either win or lose. Thus, 2(n-2)+2 points are
scored before termination.
Adversary strategy:
U-U: any
U-W: make element of W winner
U-L: make element of L loser
U-N: any
W-W: any (be consistent with before)
W-L/N: make element of W winner
L-L: any (be consistent with before)
L-N: make element of L loser
Lower bounds for the MIN and MAX – contd.
Counting-Sort(A,B,k)
• for i0 to k
• do C[i] 0
• for j 1 to length[A]
• do C[A[j]] C[A[j]]+1
• // C[i] contains number of elements equal to i.
• for i 1 to k
• do C[i]=C[i]+C[i-1]
• // C[i] contains number of elements i.
• for j length[A] downto 1
• do B[C[A[j]]] A[j]
• C[A[j]] C[A[j]]-1
Counting Sort - example
Counting Sort - analysis
1. for i0 to k (k)
2. do C[i] 0 (1)
3. for j 1 to length[A] (n)
4. do C[A[j]] C[A[j]]+1 (1) ((1) (n)= (n))
5. // C[i] contains number of elements equal to i. (0)
6. for i 1 to k (k)
7. do C[i]=C[i]+C[i-1] (1) ((1) (n)= (n))
8. // C[i] contains number of elements i. (0)
9. for j length[A] downto 1 (n)
10. do B[C[A[j]]] A[j] (1) ((1) (n)= (n))
11. C[A[j]] C[A[j]]-1 (1) ((1) (n)= (n))
Radix-Sort(A,d)
• for i1 to d
• do use a stable sort to sort A on digit i
Analysis:
Given n d-digit numbers where each digit takes on
up to k values, Radix-Sort sorts these numbers
correctly in (d(n+k)) time.
Radix sort - example
1019 1019
3075 2231
Not
2231 2225 sorted!
2225 3075
Next: Medians and Order Statistics (Ch. 9)