CSS106 Introduction to Elementary Algorithms M.Sc Askar Satabaldiyev Lecture 05: MergeSort & QuickSort
“divide and conquer” algorithm Divide the problem into subproblems Conquer the subproblems by solving them recursively. If small - solve as base cases. Combine the solutions to the subproblems into the solution for the original problem.
…more recursive calls
MergeSort 1. Divide: find middle position q 2. Conquer: recursively sort two subarrays [p..q] and [q+1..r] 3. Combine: two sorted subarrays into single sorted array [p..r]
Linear-time merging
Analysis of Merge Sort Θ(n lgn) time Not “in place”
Quick Sort Divide: by choosing pivot between [p..r] This is called partitioning Conquer: by recursively sorting subarrays [p..q-1] and [q+1..r] A i <= pivot, at the left A i > pivot, at the right Combine: do nothing…
Partitioning (less or equal)
Partitioning (greater)
Example If A J <= A r, swap(A J, A q ) Increment j, q If A J > A r, Increment j
Analysis of Quick Sort Worst-case Best-case
Average case of Quick Sort