Sorting
Input: an array of length \(n\): \(v[0,\cdots,n-1]\).
Output: a sorted array \(v\): \(v[i]\leq v[i+1]\forall 0\leq i<n-1\).
Recap Bubble Sort
Very BAD!
- Input array.
- Double nested for loop: Swap adjacent values when they are not in order.
Runtime: \(\Theta(n^2)\).
Recap Merge Sort
"Divide and Conquer" aka divide et impera
- Divide the problem into subproblems.
- Solve subproblems.
- Combine solution of subproblem into solution.
Pseudocode omitted
Running time: \(T(n)=2T(n/2)+\Theta(n)\).
By Master Theorem, \(T(n)=\Theta(n\log n)\). One can guess the answer, and proof by induction
Exercise Counting Sort
- Find the maximum value \(v\) of the input array.
- Create a new counter array with length \(v\), and initialize to \(0\).
- Scan the input array, increment on corresponding entry.
- Scan the counter array, write on input array for counting times.
Running time: \(O(n+m)\) where \(m\) is the maximum value of the input array.
Simplified Master Theorem
If running time of a divide-and-conquer algorithm is \(T(n)=aT(n/b)+\Theta(n^k)\), if
- \(a>b^k,T(n)\in\Theta(n^{\log_b a})\).
- \(a=b^k,T(n)\in\Theta(n^k\log_b n)\).
- \(a<b^k,T(n)\in\Theta(n^k)\).