Divide and conquer(QuickSort)_Algorithms
Divide and conquer(QuickSort)_Algorithms
By
Bubble Sort
◦ Design approach: incremental
◦ Sorts in place: Yes
◦ Running time: (n2)
Merge Sort
◦ Design approach: divide and conquer
◦ Sorts in place: No O(n)
◦ Running time: O(nlgn)
Quick sort
◦ Design approach: divide and conquer
◦ Sorts in place: Let’s see!!
◦ Running time: Let’s see!!
Advantages:
◦ Guaranteed to run in (nlgn)
Disadvantage
◦ Requires extra space N
Conquer
◦ Recursively sort A[p..q] and A[q+1..r] using Quicksort
Combine
◦ Trivial: the arrays are sorted in place
◦ No additional work is required to combine them
◦ The entire array is now sorted
if p < r
then q PARTITION(A, p, r)
QUICKSORT (A, p, q)
Hoare partition
◦ Select a pivot element x around which to partition
◦ Grows two regions
A[p…i] x x A[j…r]
A[p…i] x
x A[j…r]
i j
Rajesh Purkait 10/17/2021 9
A[p…r] pivot x=5
5 3 2 6 4 1 3 7 5 3 2 6 4 1 3 7
i j i j
3 3 2 6 4 1 5 7 3 3 2 6 4 1 5 7
i j i j
A[p…q] A[q+1…r]
3 3 2 1 4 6 5 7 3 3 2 1 4 6 5 7
i j j i
10/17/2021 10
Rajesh Purkait 10/17/2021 11
Alg. PARTITION (A, p, r)
p r
1. x A[p]
2. ip–1 A: 5 3 2 6 4 1 3 7
3. jr+1
i j
4. while TRUE A[p…q] ≤ A[q+1…r]
5. do repeat j j – 1
A: ap ar
6. until A[j] ≤ x
7. do repeat i i + 1 j=q i
8. until A[i] ≥ x
9. if i < j Each element is
visited once!
10. then exchange A[i] A[j]
Running time: (n)
11. else return j n=r–p+1
if p < r
then q PARTITION(A, p, r)
QUICKSORT (A, p, q)
(1) if n ≤ c
T(n) = aT(n/b) + D(n) + C(n) otherwise
T(1) = (1) 1
2 3
T(n) = T(n – 1) + n 1 1 2
n (n2)
= n k 1 ( n ) ( n 2 ) ( n 2 )
k 1
When does the worst case happen?
10/17/2021 16
Best-case partitioning
◦ Partitioning produces two regions of size n/2
Recurrence: q=n/2
T(n) = 2T(n/2) + (n)
T(n) = (nlgn) (Master theorem)
10/17/2021 17
9-to-1 proportional split
Q(n) = Q(9n/10) + Q(n/10) + n
10/17/2021 18
Rajesh Purkait 10/17/2021 19
Rajesh Purkait 10/17/2021 20
Average case
◦ All permutations of the input numbers are equally likely
◦ On a random input array, we will have a mix of well
balanced and unbalanced splits
◦ Good and bad splits are randomly distributed across
throughout the tree
partitioning cost:
n combined partitioning cost: n n = (n)
1 n-1 2n-1 = (n)
(n – 1)/2 + 1 (n – 1)/2
(n – 1)/2 (n – 1)/2