KatInterview

Adaptive Merge Sort with Comparison Counter

Heaps, Sorting & SearchAuto-graded · 20 test cases
EasyAuto-gradedHeaps, Sorting & Searchsortingdivide-and-conquerrecursion

Last 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

  1. Base Cases:
    • Arrays with 0 or 1 element require 0 comparisons and are already sorted.
  2. 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 left and right, accumulating the comparison counts from both subproblems.
  3. Adaptive Boundary Check:
    • Before performing a full merge of the sorted left and right arrays, perform 1 comparison between the last element of left (left[-1]) and the first element of right (right[0]).
    • If left[-1] <= right[0], skip the element-by-element merge. Simply concatenate left + right and return the result along with the accumulated comparison count.
  4. 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 i and j are within bounds for left and right respectively, perform 1 comparison between left[i] and right[j]:
      • If left[i] <= right[j], append left[i] to the merged output and advance i.
      • Otherwise (left[i] > right[j]), append right[j] to the merged output and advance j.
    • 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.

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.