Quick Sort
• Choose a pivot element: pick one element
from the array as pivot.
• Partition: rearrange elements in such a way
that
All elements smaller than the pivot appear
in the left part of the array.
All elements greater than the pivot appear
in the right part of the array.
Quick Sort
Pivot element will be in its proper place.
• Sort: recursively apply the quick sort to both
left and right parts.
Quick Sort Example
• Already processed or sorted
• Currently processing
I0 I1 I2 I3 I4 I5 Next
4 6 12 3 2 10 qsort(0,5)
4 3 2 10 12 6 swap 0,2
2 3 4 10 12 6 partition k=2
2 3 4 10 12 6 qsort(0,1)
qsort(3,5)
2 3 4 10 12 6 swap 0,0
2 3 4 10 12 6 partition K=0
2 3 4 10 12 6 qsort(0,-1)
qsort(1,1)
2 3 4 10 12 6 qsort(0,1)
qsort(3,5)
2 3 4 10 6 12 swap 3,4
2 3 4 6 10 12 partition k=4
2 3 4 6 10 12 qsort(3,3)
qsort(5,5)
2 3 4 6 10 12 qsort(5,5)
2 3 4 6 10 12
Quick Sort Program
Quick Sort Example
• Already processed or sorted
• Currently processing
I0 I1 I2 I3 I4 I5 Next
4 6 12 3 2 10 qsort(0,5)
4 3 2 10 12 6 swap 0,2
2 3 4 10 12 6 partition k=2
2 3 4 10 12 6 qsort(0,1)
qsort(3,5)
2 3 4 10 12 6 swap 0,0
2 3 4 10 12 6 partition K=0
2 3 4 10 12 6 qsort(0,-1)
qsort(1,1)
2 3 4 10 12 6 qsort(0,1)
qsort(3,5)
2 3 4 10 6 12 swap 3,4
2 3 4 6 10 12 partition k=4
2 3 4 6 10 12 qsort(3,3)
qsort(5,5)
2 3 4 6 10 12 qsort(5,5)
2 3 4 6 10 12
Quick Sort Analysis
• Running time:
– Worst case: O(n2)
– Best case: O(n log2n)
How the best case is O(n log2n)?
• The best case of the quick sort algorithm occurs
When pivot element is the middle value of the
values which are stored in the array.
As a result each recursion step the partition
algorithm split the given array into two equal sub
arrays.
T(n)=
For partition algorithm T(n) = c.n
(The derivation same as the derivation in the merge sort)
How the Worst case is O(n )? 2
• The worst case of quick sort arises when
Each recursion step produces an unbalanced
partition.
unbalanced partition means the partition
algorithm divides the list in such way that one
part consists of only one element and other
part consists of the rest of the element.
T(n) = T(n-1) + c.n, n>1
(pivot is 1 element so it is (n-1))
• T(n) = T(n-1) + c.n ---------------(1)
So, T(n-1)= T(n-2)+ c.(n-1) --------(2)
Again, T(n-2)= T(n-3) + c.(n-2) --(3)
So, equation (1) using (2)
=>T(n)=T(n-2) + c.(n-1) + c.n
=>T(n)=T(n-3) + c.(n-2) + c.(n-1) + c.n (using (3))
---------------------------------------------
=>T(n)= T(1) + c.(2+3+4+…..+(n-1)+n)
= 1+c. = O(n2)