Professional Documents
Culture Documents
Quicksort
HeapMaximum(A)
{
// This one is really tricky:
return A[i];
}
HeapExtractMax(A)
{
if (heap_size[A] < 1) { error; }
max = A[1];
A[1] = A[heap_size[A]]
heap_size[A] --;
Heapify(A, 1);
return max;
}
Quicksort(A, p, r)
{
if (p < r)
{
q = Partition(A, p, r);
Quicksort(A, p, q);
Quicksort(A, q+1, r);
}
}
David Luebke 8 12/08/21
Partition
1 n 1
T n T k T n 1 k n
n k 0
What is each term under the summation for?
What is the (n) term for?
2 n 1 Write it on
T k n the board
n k 0
Note: this is just like the book’s recurrence (p166),
except that the summation starts with k=0
We’ll take care of that in a second
2 n 1
T n ak lg k b n The recurrence to be solved
n k 1
2 n 1 2 n 1
ak lg k b n Distribute
What arethewe
summation
doing here?
n k 1 n k 1
2a n 1 2b
k lg k ( n 1) n Evaluate the summation:
What are we doing here?
b+b+…+b = b (n-1)
n k 1 n
2a n 1
k lg k 2b n Since n-1<n,
What 2b(n-1)/n
are we < 2b
doing here?
n k 1
This summation gets its own set of slides later
David Luebke 34 12/08/21
Analyzing Quicksort: Average Case
2a n 1
T n k lg k 2b n The recurrence to be solved
n k 1
2a 1 2 1 2
n lg n n 2b n What
We’llthe
prove
hell?this later
n 2 8
a
an lg n n 2b n Distribute
What arethewe(2a/n)
doingterm
here?
4
a
an lg n b n b n Remember, our goal is to get
What are we doing here?
4 T(n) an lg n + b
an lg n b Pick a large enough that
How did we do this?
an/4 dominates (n)+b
David Luebke 35 12/08/21
Analyzing Quicksort: Average Case
So T(n) an lg n + b for certain a and b
Thus the induction holds
Thus T(n) = O(n lg n)
Thus quicksort runs in O(n lg n) time on average
(phew!)
Oh yeah, the summation…
k lg k k lg k k lg k
Split the summation for a
What are we doing here?
tighter bound
k 1 k 1 k n 2
n 2 1 n 1
k lg k k lg n
The lg k in the second term
What are we doing here?
is bounded by lg n
k 1 k n 2
k lg k k lg k lg n k
The summation bound so
far
k 1 k 1 k n 2
n 2 1 n 1
k lg n 2 lg n k
The lg k in the first term is
What are we doing here?
bounded by lg n/2
k 1 k n 2
n 2 1 n 1
k lg n 1 lg n
k 1
k
k n 2
lg n/2
What= lg n we
are - 1 doing here?
n 2 1 n 1
lg n 1 k lg n k
Move (lg n - 1) outside the
What are we doing here?
summation
k 1 k n 2
k lg k lg n 1 k lg n k
The summation bound so
far
k 1 k 1 k n 2
n 2 1 n 2 1 n 1
lg n k
k 1
k lg n
k 1
k
k n 2
Distribute
What are wethe (lg nhere?
doing - 1)
n 1 (n) n 2 1
lg n
2
k
k 1
TheWhat
Guassian
are weseries
doing here?
1 1 n n
n n 1 lg n 1 X Guassian
What are series
we doing?
2 2 2 2
1 2
2
n lg n n lg n n
1 2 n
8 4
Multiply it
What are we doing?
all out
n 1
1 2 1 2 n
k 1
k lg k n lg n n lg n n
2 8 4
1 2 1 2
n lg n n when n 2
2 8
Done!!!