Merge Sort

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Merge Sort divides the array, sorts recursively, and merges two sorted halves. Time $\Theta(n \log n)$, additional linear memory.

Stable and predictable. Good as a teaching example for Divide-and-Conquer.

Diagram

$$T(n)=2T(n/2)+\Theta(n)$$

Merge two sorted runs: Merge Sorted Array [1].

Where used

Stable $O(n \log n)$ reference, external sorting (runs on disk), ancestor of TimSort. Parallelizable over independent halves.

Depth

Merge Sort recursively breaks the input into halves, sorts both parts, and combines them in order. During merging, one pointer points to the smallest unmerged element of each half. The smaller is output until one half is exhausted.

The recursion has logarithmically many levels, and at each level, all elements are processed in total. Classic array implementations use an additional buffer on the order of the input size. By adopting from the left half first in case of equality, stability is achieved.

Difficulty levels

  1. Merge two sorted sequences using pointers.
  2. Connect work per recursion level and the number of levels.
  3. Reuse buffer and ensure stable equality handling.

Pitfalls

After the main loop, the remaining elements of the non-exhausted half must be copied. Incorrect interval boundaries can lead to lost or double-processed elements, especially with odd lengths.


Sources

University approvals: 0
Tasks
Question 1

Additional space of classic Merge Sort:

Question 2

How does the mixing of two sorted halves remain stable?

Question 3

Implement Merge Sort in ascending order.

Hint

Arrays.copyOfRange(a, from, to) copies a half-open range. A helper array is created with new int[length].

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy