Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
of
Quick-sort
WORST-CASE ANALYSIS
In
worst-case
partitioning
(unbalanced):
T(n) = T(n-1) + T(0) + (n)
Running time, T(n) = (n2)
WORST-CASE ANALYSIS
A recursion tree for QUICKSORT in which the partition
procedure always puts only a single element on one
side of the partition:
WORST-CASE ANALYSIS
The substitution method for solving recurrences
comprises two steps:
1. Guess the form of the solution.
2. Use mathematical induction to find the constants
and show that the solution works.
We can use the substitution method to establish
either upper or lower bounds on a recurrence.
WORST-CASE ANALYSIS
Using substitution method, we can show that
the running time of quicksort is O(n2).
Let T(n) be worst-case time of an input size n
We have the recurrence
T(n) = max (T(q) + T(n-q-1)) + (n)
0 q n-1
WORST-CASE ANALYSIS
Guess that T(n) = O(n2)
The substitution method requires us to prove that :
T(n) = cn2
for constant c > 0.
Induction hypothesis:
any
k< n
Yielding
T(q) + T(n-q-1) cq2 +
c(n-q-1)2
Substituting into the recurrence, we get
T(n) max (cq2 + c(n-q-1)2)
+ (n)
n-1 (q2 + (n-q-1)2) +
= 0c qmax
(n)
0 q n-1
WORST-CASE ANALYSIS
T(n) c max (q2 + (n-q1)2) + (n)
0 q n-1
The expression q2 + (n-q-1)2 achieves a maximum
over the range 0 q n-1 at one of the
endpoints
T(n) cn2 c(2n-1) + (n)
cn2
since we can pick the constant c large enough
so that the c(2n-1) term dominates the (n)
term.
Thus, T(n) = O(n2)
PARTITION(A, p, r)
1 x = A[r]
2i=p-1
3 for j = p to r - 1
4 if A[j] x
5
i=i+1
6
exchange A[i]
with A[j]
7 exchange A[i + 1]
p,with
r) A[r]
8 return i + 1
RANDOMIZED-QUICKSORT(A,
1 if p < r
2
q
=
RANDOMIZEDPARTITION(A, p, r)
3 RANDOMIZED-QUICKSORT(A, p,
q 1)
4 RANDOMIZED-QUICKSORT(A, q
X =:
Taking expectations of both sides,
E[X] = E
=
=
from
+
from
Zij}
Pr
+ {zj is first pivot chosen
Zij}
2
E[X] =
For k = j i,
E[X] =
<
Thus,
2and
1
,we get
E[X] =
Presented By:
Sahil Arora
133137