int count = 0; void mergeSort(int arr[], int l, int r) { count++; if (l >= r) return; int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); // merging code omitted for brevity } int main() { int arr[4] = {4, 3, 2, 1}; mergeSort(arr, 0, 3); std::cout << count << std::endl; return 0; }
The mergeSort function is called once for the whole array, then recursively for each half until single elements are reached.
For size 4, calls are: mergeSort(0,3), mergeSort(0,1), mergeSort(0,0), mergeSort(1,1), mergeSort(2,3), mergeSort(2,2), mergeSort(3,3) totaling 7 calls.
Here, a=3, b=4, so log_b a = log_4 3 â 0.792.
f(n) = n = n^1 = Ω(n^{0.792 + Δ}) for Δ â 0.208.
Regularity condition: a f(n/4) = 3*(n/4) = 0.75n †c n for c=0.75 < 1, holds for all n ℠1.
Thus, Case 3 applies: T(n) = Î(n).
int T(int n) { if (n == 1) return 1; return 2 * T(n / 2) + n; } int main() { std::cout << T(0) << std::endl; return 0; }
The base case is for n==1, but main calls T(0).
For n=0, it calls T(0/2)=T(0) again, causing infinite recursion and stack overflow.
Here, a=7, b=2, so log_b a = log_2 7 â 2.807.
Since f(n) = O(n^2) which is smaller than n^{log_b a}, the time complexity is O(n^{log_2 7}).
Binary search splits the array into halves each step, so T(n) = T(n/2) + O(1).
Solving this recurrence gives O(log n) time complexity.
