Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Algorithms and Computations Complexity

Quick sort
Lecture 5
References:
Introduction to Algorithms, Thomas H. Cormen, 2ed edition,

Instructor: Prashant mishra


BIAS,Bhimtal
Quick sort
• Quick sort, like merge sort, is based on the divide-and-conquer
paradigm introduced in previous section. Here is the three-step
divide-and-conquer process for sorting typical sub array
A[p.…..r].
• Divide: Partition (rearrange) the array A[p……r] into two
(possibly empty) sub arrays A[p…...q – 1] and A[q + 1…...r]
such that each element of A[p…...q – 1] it less than or equal to
A[q], which is, in turn, less than or equal to each element of
A[q + 1..r]. Compute the index q as part of this partitioning
procedure.
• Conquer: Sort the two sub arrays A [p ..q – 1] and A[q + 1..r]
by recursive calls to quick sort.
• Combine: Since the sub arrays are sorted in place, no work is
needed to combine them: the entire array A[p…...r] is now
sorted.
QUICKSORT (A, p, r)
1. if p < r
2. then q ← Partition (A, p, r)
3. Quick sort (A, p, q – 1)
4. Quick sort (A, q + 1, r)

To sort an entire array A, the initial call is


QUICKSORT (A, 1, length [A]).
Partitioning the Array

PARTITION (A, p, r)
1. x ← A [r]
2. i ← p – 1
3. for j ← p to r – 1
4. do if A[ j] ≤ x
5. then i ← i + 1
6. exchange A [i] ↔ A [j]
7. exchange A [i + 1] ↔ A [r]
8. return i + 1
Figure below shows the operation of
PARTITION on an 8-element array.
PARTITION always selects an element x = A
[r] as a pivot element around which to partition
the sub array A[p…...r].
Partitioning the array
i p, j r

(a) 2 8 7 1 3 5 6 4

p, i j r

(b) 2 8 7 1 3 5 6 4

p. i j r

(c) 2 8 7 1 3 5 6 4

p, i j r

(d) 2 8 7 1 3 5 6 4

p i j r

(e) 2 1 7 8 3 5 6 4

p i j r

(f) 2 1 3 8 7 5 6 4

p i j r

(g) 2 1 3 8 7 5 6 4

p i j r

(h) 2 1 3 8 7 5 6 4

p i r

(i) 2 1 3 4 7 5 6 8

The Operation of PARTITION on a Sample Array


Worst-case of quick sort

• Input sorted or reverse sorted.

• Partition around min or max element.

• One side of partition always has no elements.


T(n) = T(0) + T(n–1) + cn
Best case partitioning
In the most even possible split PARTITION
produce two sub problems each of size no
more than n/2 since one is of size n/2 and
one of size n/2 -1 in this case quick sort run
much faster .
The recurrence for running time is then
T(n)<= 2T(n/2) + Θ (n)
Which by case 2 of master theorem has the
solution T(n) = O(nlgn)
Balanced partitioning
The average case running time of quicksort is
much closer to the best case than to the worst
case .
Suppose for ex. That the PARETITION
algorithm always produce a 9:1 proportional
split .
We obtain the recurrence
T(n) <=T(9n/10) +T(n/10)+cn
The total cost of quick sort is O(nlgn)

You might also like