Professional Documents
Culture Documents
1
University Institute of Engineering (UIE)
QUICK SORT
2
University Institute of Engineering (UIE)
Divide and Conquer
Approach
• Quick-sort is a sorting algorithm
based on the divide-and-
conquer paradigm: x
– Divide: pick a random element
x (called pivot) and partition S
into
• L elements less than x x
• E elements equal x L E G
• G elements greater than x
– Recur: sort L and G
– Conquer: join L, E and G
– Base case : List of size 0 or 1. x
6
University Institute of Engineering (UIE)
Analysis
• Assumptions:
– A pivot at the last element of the array.
• Running time
– pivot selection: constant time O(1)
– partitioning: linear time Θ(n) where n=r-p+1
– running time of the two recursive calls
• T(N)=T(i)+T(N-i)+cN where c is a constant
– i: number of elements in L
– Rest n-i present in G or vice versa
7
University Institute of Engineering (UIE)
Worst-case Running Time
• The worst case for quick-sort occurs when the pivot is
the unique minimum or maximum element
• One of L and G has size n 1 and the other has size 0
• The running time is proportional to the sum
n (n 1) … 2
• Thus, the worst-case running time of quick-sort is O(n2)
depth time
0 n
1 n1
…
… …
n1 1 8
University Institute of Engineering (UIE)
Picking the Pivot
• Random number
• Median of the array
• Median of the three
9
University Institute of Engineering (UIE)
Pivot : Any Random
10
University Institute of Engineering (UIE)
Pivot : The Median of Array
11
University Institute of Engineering (UIE)
Pivot: median of three
• \We will use median of three
– Compare just three elements: the leftmost, rightmost and center
– Swap these elements if necessary so that
• A[left] = Smallest
• A[right] = Largest
• A[center] = Median of three
– Pick A[center] as the pivot
12
University Institute of Engineering (UIE)
Pivot: median of three
pivot
3 12
13
University Institute of Engineering (UIE)
Expected Running Time
• Consider a recursive call of quick-sort on a sequence of size s
– Good call: the sizes of L and G are each less than 3s4
– Bad call: one of L and G has size greater than 3s4
7 2 9 43 7 6 19 7 2 9 43 7 6 1
• A call is good with probability 12
– 1/2 of the possible pivots cause good calls:
2 4 3 1 7 9 7 1 1 1 7294376
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
16
University Institute of Engineering (UIE)
References
• Introduction to Algorithms
Thomas H. Cormen,
Charles E. Leiserson
Ronald L. Rivest
• Data Structures Using C and C++
Andrew S. Tanenbaum
• www.utdallas.edu/~daescu/QuickSort.ppt
• http://en.wikipedia.org/wiki/Quicksort
17
University Institute of Engineering (UIE)
•Thanks
18
University Institute of Engineering (UIE)