Merge_Quick_sort_notes
Merge_Quick_sort_notes
8 2 9 4 5 3 1 6
2 4 8 9 1 3 5 6
Auxiliary array
2 4 8 9 1 3 5 6
Auxiliary array
1
2 4 8 9 1 3 5 6
Auxiliary array
1 2 3 4 5
i j normal
target
Left completed
copy i j
first
target
target
Merge by 1
Merge by 2
Merge by 4
Merge by 8
Merge by 1
Merge by 2
Merge by 4
Merge by 8
Merge by 16
S1 0 31
S2 75
partition S
43 65
13 81
92
26 57
QuickSort(S1) and
S1 S2 QuickSort(S2)
0 13 26 31 43 57 65 75 81 92
S 0 13 26 31 43 57 65 75 81 92 Voila! S is sorted
[Weiss]
8 1 4 9 0 3 5 2 7 6
Median of 0, 6, 8 is 6. Pivot is 6
0 1 4 9 7 3 5 2 6 8
i j
Place the largest at the right
and the smallest at the left.
Swap pivot with next to last element.
Example
i j
0 1 4 9 7 3 5 2 6 8
i j
0 1 4 9 7 3 5 2 6 8
i j
0 1 4 9 7 3 5 2 6 8
i j
0 1 4 2 7 3 5 9 6 8
0 1 4 2 7 3 5 9 6 8
i j
0 1 4 2 7 3 5 9 6 8
i j
0 1 4 2 5 3 7 9 6 8
i j
0 1 4 2 5 3 7 9 6 8
j i
0 1 4 2 5 3 7 9 6 8 Cross-over i > j
j i
0 1 4 2 5 3 6 9 7 8
37
Quicksort Best Case
Performance
• Algorithm always chooses best pivot
and splits sub-arrays in half at each
recursion
› T(0) = T(1) = O(1)
• constant time if 0 or 1 element
› For N > 1, 2 recursive calls plus linear time
for partitioning
› T(N) = 2T(N/2) + O(N)
• Same recurrence relation as Mergesort
› T(N) = O(N log N)
Divide and Conquer Sorting 38
Quicksort Worst Case
Performance
• Algorithm always chooses the worst pivot –
one sub-array is empty at each recursion
› T(N) a for N C
› T(N) T(N-1) + bN
› T(N-2) + b(N-1) + bN
› T(C) + b(C+1)+ … + bN
› a +b(C + (C+1) + (C+2) + … + N)
› T(N) = O(N2)
• Fortunately, average case performance is
O(N log N)
Divide and Conquer Sorting 39
Properties of Quicksort
• Not stable because of long distance
swapping.
• No iterative version (without using a stack).
• Pure quicksort not good for small arrays.
• “In-place”, but uses auxiliary storage because
of recursive call (O(logn) space).
• O(n log n) average case performance, but
O(n2) worst case performance.
42
2/19/03 Divide and Conquer Sorting - 43
Lecture 14
44
Recursive Max Min Algorithm
45
46
47
48
Recursive Binary Search
49
56
57
58