Lecture 008

divide and conquer: divide in half, solve problem in small, put together big solution.

Merge Function

Fast Sorting Algorithms

Merge sort

Cost:

Recursive Safety

• INITialization: safety of initial call of the function

• PREServation: From preconditions to safety of recursive calls

• EXIT: from postconditions of recursive calls to postconditions

• TERMination: base case handles input smaller than some bound, input of recursive calls strictly smaller than input of function

Quick sort

• if median, complexity = merge sort O(nlogn)

• if unlucky, complexity = selection sort O(n^2)

• if average-case, O(nlogn)

How to pick pivot:

1. pick A[lo]
2. random pick A[i]
3. pick 3 number and compare them

Stable Sorting

Best case complexity

• Linear search O(1)

• Binary search O(1)

Selection Sorting Merge Sort Quick Sort
Worst Case n^2 n log(n) n^2
Average Case n^2 n log(n) n log(n)
Best Case n^2 n log(n) n log(n)
In-Place Y N Y
Stable N Y Y

stable: whether sort among 2 dimension produce the same outcome

Table of Content