What is merge sort?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for Data Structures & Algorithms development. It reveals whether you understand the building blocks that more complex concepts rely on.
Answer
Merge sort is a divide-and-conquer sorting algorithm that recursively divides the array into halves, sorts each half, then merges the sorted halves. It guarantees O(n log n) performance in all cases. Algorithm: (1) If the array has 0 or 1 elements, return (base case); (2) Divide: split array in half; (3) Conquer: recursively sort each half; (4) Combine: merge the two sorted halves into one sorted array. Merge operation: use two pointers on each half, compare, and copy the smaller element to the result; O(n). Time: O(n log n) — n levels of recursion, O(n) work per level. Space: O(n) auxiliary space for the merge step (not in-place). Stable: yes. Best for: linked lists (O(1) extra space possible), external sorting (sorting data too large for RAM — merge sorted chunks from disk), when O(n log n) worst case is required (unlike quicksort). Java's Arrays.sort() for objects uses TimSort (merge sort + insertion sort). Disadvantage: requires O(n) extra space; slightly slower than quicksort in practice due to extra memory operations. Merge sort demonstrates divide-and-conquer, recurrence relations T(n) = 2T(n/2) + O(n) → O(n log n), and the master theorem.
Pro Tip
This topic has Data Structures & Algorithms-specific nuances that differ from general programming. Highlighting those nuances in your answer shows expertise rather than generic knowledge.