Adaptive Merge Sort with Comparison Counter
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Count element-level comparisons during an adaptive divide-and-conquer merge sort.
Implement an adaptive variant of merge sort that returns both the fully sorted array and the total count of element-to-element comparisons performed throughout the execution.
Sorting Algorithm Specification
- Base Cases:
- Arrays with
0or1element require0comparisons and are already sorted.
- Arrays with
- Splitting:
- Split an array of length $N$ into two subarrays at index $\lfloor N / 2 \rfloor$:
left = arr[0 : N//2]right = arr[N//2 : N]
- Recursively sort both
leftandright, accumulating the comparison counts from both subproblems.
- Split an array of length $N$ into two subarrays at index $\lfloor N / 2 \rfloor$:
- Adaptive Boundary Check:
- Before performing a full merge of the sorted
leftandrightarrays, perform 1 comparison between the last element ofleft(left[-1]) and the first element ofright(right[0]). - If
left[-1] <= right[0], skip the element-by-element merge. Simply concatenateleft + rightand return the result along with the accumulated comparison count.
- Before performing a full merge of the sorted
- Element-wise Merge:
- If the adaptive check fails (
left[-1] > right[0]), proceed with a standard two-pointer merge. - For each iteration of the merge loop where pointers
iandjare within bounds forleftandrightrespectively, perform 1 comparison betweenleft[i]andright[j]:- If
left[i] <= right[j], appendleft[i]to the merged output and advancei. - Otherwise (
left[i] > right[j]), appendright[j]to the merged output and advancej.
- If
- Once one pointer reaches the end of its array, append all remaining elements from the other array to the output without making any further comparisons.
- If the adaptive check fails (
Constraints
- $0 \le \text{len}(arr) \le 10^5$
- $-10^9 \le arr[i] \le 10^9$
- The input array must not be mutated.
- Comparison counting must strictly reflect the steps outlined above.
Examples
Example 1
Input: adaptive_merge_sort([1, 2, 3, 4])
Output: [[1, 2, 3, 4], 3]
Example 2
Input: adaptive_merge_sort([4, 3, 2, 1])
Output: [[1, 2, 3, 4], 7]
Hints
Hint 1
Handle arrays of length 0 or 1 as base cases returning 0 comparisons.
Hint 2
Always increment the comparison count by 1 for the adaptive check (left[-1] <= right[0]).
Hint 3
Only count comparisons made between elements of left and right inside the merge loop; appending remaining tail elements costs 0 comparisons.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The algorithm follows a classic divide-and-conquer strategy enhanced by an adaptive shortcut:
- Recursion: Divide the array into two halves at
mid = len // 2. Recursively sort both halves while tracking comparison counts. - Adaptive Optimisation: Check if
left[-1] <= right[0]. This requires 1 comparison:- If true, all elements in
leftare less than or equal to all elements inright. Concatenateleft + rightdirectly.
- If true, all elements in
- Standard Merge: If the condition fails, merge the two sorted halves element by element using two pointers. Each check
left[i] <= right[j]increments the comparison count by 1. Remaining elements appended after one half is exhausted do not require additional comparisons.
Complexity Analysis
- Time Complexity:
- Best Case (Already Sorted): $\mathcal{O}(N)$. At every step, the boundary check succeeds in 1 comparison, so merging takes $\mathcal{O}(1)$ work per node in the recursion tree.
- Worst / Average Case: $\mathcal{O}(N \log N)$. In the worst case, every boundary check fails and full merges are executed, matching standard merge sort runtime.
- Space Complexity: $\mathcal{O}(N)$ auxiliary space for storing the merged lists at each recursion level and $\mathcal{O}(\log N)$ stack space.
Python Source Code
from typing import List, Tuple
def adaptive_merge_sort(arr: List[int]) -> Tuple[List[int], int]:
def sort(values: List[int]) -> Tuple[List[int], int]:
n = len(values)
if n <= 1:
return values[:], 0
mid = n // 2
left, left_count = sort(values[:mid])
right, right_count = sort(values[mid:])
comparisons = left_count + right_count
# Adaptive check
comparisons += 1
if left[-1] <= right[0]:
return left + right, comparisons
merged = []
i = 0
j = 0
while i < len(left) and j < len(right):
comparisons += 1
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged, comparisons
return sort(arr)