Given:
Return:
Imagine you have two stacks of sorted cards, and you wanted to make one sorted pile in the center.
Main loop (until one stack is empty):
Aftewards move leftover stack onto center.
merge)Class “divide and conquer” algorithm
\(O(N) work + recursion case\)
At each level we have linear work across all subproblems combined, and there are only logarithmically many levels.
merge does O(N) workThe array is divided in half \(\log N\) times (the depth of the recursion tree). At each level, we do \(O(N)\) work to merge all subarrays at that level.
Total work is \(O(N) * \log N\) = \(O(N \log N)\)
The recurrence relation is \(T(N) = 2*T(\frac{N}{2}) + O(N)\)
Total runtime is \(O(N \log N)\)