using System; class Program { static int callCount = 0; static void MergeSort(int[] arr, int left, int right) { callCount++; if (left >= right) return; int mid = (left + right) / 2; MergeSort(arr, left, mid); MergeSort(arr, mid + 1, right); } static void Main() { int[] array = {5, 3, 8, 6}; MergeSort(array, 0, array.Length - 1); Console.WriteLine(callCount); } }
The merge sort splits the array recursively until single elements remain. For an array of size 4, the calls are:
- Call 1: full array (0-3)
- Call 2: left half (0-1)
- Call 3: left half of left half (0-0)
- Call 4: right half of left half (1-1)
- Call 5: right half (2-3)
- Call 6: left half of right half (2-2)
- Call 7: right half of right half (3-3)
Total calls = 7.
Binary search splits the array in half each time and does a constant amount of work to compare the middle element. So the recurrence is T(n) = T(n/2) + O(1).
using System; class Program { static int Recurrence(int n) { if (n == 1) return 1; return 2 * Recurrence(n / 2) + n; } static void Main() { Console.WriteLine(Recurrence(8)); } }
The recurrence expands as:
- T(8) = 2*T(4) + 8
- T(4) = 2*T(2) + 4
- T(2) = 2*T(1) + 2
- T(1) = 1
Calculating bottom-up:
- T(1) = 1
- T(2) = 2*1 + 2 = 4
- T(4) = 2*4 + 4 = 12
- T(8) = 2*12 + 8 = 32
But the code returns 24 because integer division truncates and the base case is at n==1, so the calls are correct and output is 24.
using System; class Program { static int partitionCalls = 0; static int Partition(int[] arr, int low, int high) { partitionCalls++; int pivot = arr[high]; int i = low - 1; for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp1; return i + 1; } static void QuickSort(int[] arr, int low, int high) { if (low < high) { int pi = Partition(arr, low, high); QuickSort(arr, low, pi - 1); QuickSort(arr, pi + 1, high); } } static void Main() { int[] array = {4, 2, 7, 1}; QuickSort(array, 0, array.Length - 1); Console.WriteLine(partitionCalls); } }
Partition is called once for the full array (0-3), then for the left subarray (0-1), and then for the right subarray (3-3) which does not call partition because low is not less than high. So total calls = 3.
Here, a=3, b=4, so log_b(a) = log_4(3) ≈ 0.792. The function f(n) = n log n = Θ(n^{1} * log n). Since 1 > 0.792, f(n) grows faster than n^{log_b(a)} but not polynomially larger. This fits Case 2 of the Master Theorem where f(n) = Θ(n^{log_b(a)} * log^k n) with k=1.
