CSE101 L14 DivideConquer - Sort
CSE101 L14 DivideConquer - Sort
1
The divide-and-conquer
design paradigm
MERGE-SORT A[1 . . n]
1. If n = 1, done.
2. Recursively sort A[ 1 . . n/2]
and A[ n/2+1. . n ] .
3. “Merge” the 2 sorted lists.
1
Merging two sorted arrays
L R L R
20 12 20 12
13 11 13 11
7 9 7 9 j
2 1 i 2
1
Merging two sorted arrays
L R
20 12 20 12
13 11 13 11
7 9 7 9 j
2 1 i 2
1 2
Merging two sorted arrays
L R
20 12 20 12 20 12
13 11 13 11 13 11
7 9 7 9 i 7 9 j
2 1 2
1 2
Merging two sorted arrays
20 12 20 12 20 12
13 11 13 11 13 11
7 9 7 9 7 9
2 1 2
1 2 7
Merging two sorted arrays
20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7
Merging two sorted arrays
20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11 12
Merging two sorted arrays
20 12 20 12 20 12 20 12 20 12 20 12
13 11 13 11 13 11 13 11 13 11 13
7 9 7 9 7 9 9
2 1 2
1 2 7 9 11 12
1. Divide: Trivial.
2. Conquer: Recursively sort 2 subarrays.
3. Combine: Linear-time merge.
T(n) = 2 T(n/2) + Θ(n)
Θ(1) if n = 1;
T(n) =
2T(n/2) + Θ(n) if n > 1.
𝑇 𝑛 = Θ(𝑛 log 𝑛)
Using Recursion tree
…
Θ(1) #leaves = n Θ(n)
Total = Θ(n lg n)
Divide and conquer
Quicksort an n-element array:
1. Divide: Partition the array into two subarrays
around a pivot x such that elements in lower
subarray ≤ x ≤ elements in upper subarray.
≤x x ≥x
2. Conquer: Recursively sort the two subarrays.
3. Combine: Trivial.
Key: Linear-time partitioning subroutine.
Quicksort
• Quicksort Pseudocode
Θ(1)
Worst-case recursion tree
T(n) = T(0) + T(n–1) + cn
cn n
Θ(1) c(n–1) Θ∑ k = Θ(n2 )
k =1
Θ(1) c(n–2)
h=n T(n) = Θ(n) + Θ(n2)
Θ(1)
= Θ(n2)
Θ(1)
Best-case analysis
cn
T (101 n ) T (109 n )
Analysis of “almost-worst” case
cn
1
10
cn 9 cn
10
T (100
1
n )T (100
9
n ) T (100
9
n )T (100
81
n)
Analysis of “almost-worst” case
cn cn
1
10
cn 9 cn cn
10
log10/9n
1 cn 9 cn 9cn 81 cn
cn
100 100 100 100
…
Θ(1) O(n) leaves
Θ(1)
Analysis of “almost-worst” case
cn cn
1
10
cn 9 cn cn
10
log10 log10/9n
n 1 cn 9 cn 9cn 81 cn
cn
100 100 100 100
…
Θ(1) O(n) leaves
• Recurrence Relations
• Solving Recurrences
• Divide & Conquer
• Sorting using Divide & Conquer Multiplication
– Merge sort Algorithms
– Quick sort
43