2. Quick Sort : Based on Divide and Conquer
paradigm.
One of the fastest in-memory sorting algorithms
(if not the fastest)
2
is a very efficient sorting algorithm
designed by C.A.R.Hoare in 1960.
Consists of two phases:
Partition phase
Sort phase
QQuuiicckkSSoorrtt
5. AAllggoorriitthhmm:: QQuuiicckk SSoorrtt
Procedure QuickSort ( A, l, r )
5
if ( r > l ) then
j = partition ( A, l, r );
QuickSort ( A, l, j - 1 );
QuickSort ( A, j + 1 , r );
end of if.
6. r
9 8 2 3 88 34 5 10 11 0
5 8 2 3 0 9 34 11 10 88
6
Partition
l
l j r
A
A
7. 7
AAllggoorriitthhmm:: PPaarrttiittiioonn
Function Partition (A, l, r )
v = a[ l ]; i = l ; j = r+1;
do
do i = i +1
while (a[i] <= v) and (i < n );
do j = j – 1
while (a[ j] >= v) and (j > 2);
if (i<j) then swap (a[i], a[j]);
while j >= i;
a [ l ] = a[ j ]; a[ j ] = v;
return ( j );
8. v = a[ l ]; i = l ; j = r+1;
do
do i = i +1 while (a[i] <= v) and (i < n );
do j = j – 1 while (a[ j] >= v) and (j > 2);
if (i<j) then swap (a[i], a[j]);
i v 9 j
9 8 2 3 88 34 5 10 11 0
i j
9 8 2 3 88 34 5 10 11 0
i j
9 8 2 3 0 34 5 10 11 88
9 8 2 3 0 34 5 10 11 8
88
i j
while j >= i;
a [ l ] = a[ j ]; a[ j ] = v;
return ( j );
9. 9
i j
v = a[ l ]; i = l ; j = r+1;
do
9 8 2 3 0 5 34 10 11 88
j i
9 8 2 3 0 5 34 10 11 88
j i
5 8 2 3 0 9 34 10 11 88
out of outer
repeat loop
do i = i +1 while (a[i] <= v) and (i < n );
do j = j – 1 while (a[ j] >= v) and (j > 2);
if (i<j) then swap (a[i], a[j]);
while j >= i;
a [ l ] = a[ j ]; a[ j ] = v;
return ( j );
10. WWoorrsstt CCaassee TTiimmee CCoommpplleexxiittyy ooff QQuuiicckkSSoorrtt
The number of comparisons taken by Quicksort in the worst
case are O(n²).
Proof:
Worst case occurs when Partition results in a zero size and
an n-1 size partition.
10
12. BBeesstt CCaassee TTiimmee CCoommpplleexxiittyy ooff QQuuiicckkSSoorrtt
The number of comparisons taken by quicksort in the best
case are O(n lg(n)).
Proof:
If the partitioning procedure produces two regions of size n/2,
quicksort runs much faster,
Since we are dividing our input(n) with 2, so base case will
arise after lg(n) iterations.
Cost of each iteration is O(n), so the best case time
complexity of quicksort is O(n lg(n)).
12