Building Sorted Arrays with Merge Sort

Merge sort sorts a sequence by dividing it into smaller sequences, sorting those pieces, and merging the sorted results. You can use it to arrange numbers or records by a chosen key, such as a submission time. Its central advantage is predictable growth in running time: even an unfavourable input follows the same balanced splitting structure.

Split until the pieces are simple

In the usual top-down implementation, split an array into two contiguous halves. Recursively sort each half, meaning that you apply the same procedure to that smaller section. An array containing zero or one item is already sorted, so it needs no further splitting. This stopping condition also prevents recursion from continuing indefinitely.


When the length is odd, the halves differ in size by one. Their original contents do not need to be ordered. Splitting only decides which items belong to each smaller problem; the merging stage establishes their order.


An array splits into single items and then merges into progressively larger sorted arrays.


Merge two sorted pieces

To merge two sorted arrays, keep a position at the first unconsumed item in each. Compare these two items and append the smaller one to the output. Advance only the position belonging to the item you selected. Repeat until one input is exhausted, then append the other input's remaining items without further key comparisons.


This procedure works because each input is already sorted. Its first unconsumed item is its smallest remaining item, so the smaller of the two front items is the smallest item remaining overall.


Example: Merge [1,6][1,6] with [4,10][4,10]. Compare 11 with 44 and select 11. Then compare 66 with 44 and select 44. Compare 66 with 1010 and select 66. Append the remaining 1010, giving [1,4,6,10][1,4,6,10] after three key comparisons.



Stability means preserving the original relative order of records with equal keys. For a stable merge, select from the left half when the keys are equal. The left half contains earlier records from the original sequence. If every recursive merge follows this rule, equal-key records keep their original relative order throughout the sort.



Work and storage

Merging sorted arrays of lengths aa and bb processes a+ba+b items. If both inputs are nonempty, it uses at most a+b−1a+b-1 key comparisons; copying a leftover item does not require another key comparison.


For powers of two, the standard running-time relationship is


T(n)=2T(n/2)+Θ(n),T(1)=Θ(1).T(n)=2T(n/2)+\Theta(n),\qquad T(1)=\Theta(1).


Here, Θ\Theta expresses the order of growth. The two recursive calls sort the halves, and the linear term covers their merge. There are log⁡2n\log_2 n merge levels, with total work proportional to nn at each level. Therefore,


T(n)=Θ(nlog⁡2n).T(n)=\Theta(n\log_2 n).


The same growth rate applies when the length is not a power of two. For the standard array implementation that always performs its merges:


Quantity

Already sorted input

Worst-case input

Running time

Θ(nlog⁡n)\Theta(n\log n)

Θ(nlog⁡n)\Theta(n\log n)

Reusable temporary buffer

Θ(n)\Theta(n) slots

Θ(n)\Theta(n) slots

Maximum recursive call depth

Θ(log⁡n)\Theta(\log n)

Θ(log⁡n)\Theta(\log n)


These storage bounds assume index ranges and one reusable buffer rather than newly retained copies at every level. The call stack adds logarithmic space, so total auxiliary space remains linear. An implementation that explicitly skips already ordered merges can have different best-case behaviour.

What to remember

  • Split down to arrays of at most one item.
  • Merge by comparing the two current front items.
  • Append leftovers without further key comparisons.
  • Choose the left item on equality to preserve stability.
  • Standard array merge sort takes Θ(nlog⁡n)\Theta(n\log n) time and Θ(n)\Theta(n) auxiliary space.

Example: Sorting Submission Identifiers

Example: A submission system uses standard top-down merge sort to arrange the identifiers [42,18,35,9,27,14,31,22][42,18,35,9,27,14,31,22] in ascending order. It splits into equal contiguous halves until single items remain and performs every merge.


A key comparison compares the current front values of two nonempty inputs. Count these comparisons only; copying leftover items and checking array positions do not count.


Eight submission identifiers divide into two halves and then four adjacent pairs.


a) Find the two sorted length-four halves that will enter the final merge.


First split every pair into single items, then merge each pair. The first two sorted pairs contain ________ and ________, respectively. The other two sorted pairs are [14,27][14,27] and [22,31][22,31].


For the left length-four half, merge [18,42][18,42] with [9,35][9,35]:

  1. Compare 1818 with 99; output 99.
  2. Compare 1818 with 3535; output 1818.
  3. Compare 4242 with 3535; output 3535.
  4. The right input is empty, so append 4242 without another key comparison.

For the right length-four half, merge [14,27][14,27] with [22,31][22,31]:

  1. Compare 1414 with 2222; output 1414.
  2. Compare 2727 with 2222; output 2222.
  3. Compare 2727 with 3131; output 2727.
  4. The left input is empty, so append 3131 without another key comparison.

The two sorted halves are [9,18,35,42][9,18,35,42] and [14,22,27,31][14,22,27,31].


b) Perform the final merge. State the sorted array and the number of key comparisons in this merge.


Start at the first item of each sorted half. Select the smaller current item and advance only its input position.

  1. Compare 99 with 1414; output 99.
  2. Compare 1818 with 1414; output 1414.
  3. Compare 1818 with 2222; output 1818.

The output prefix is now ________. Continue with the current items 3535 and 2222.

  1. Compare 3535 with 2222; output 2222.
  2. Compare 3535 with 2727; output 2727.
  3. Compare 3535 with 3131; output 3131.

The right input is now empty. Append 3535 and 4242 from the left input. Appending those leftovers requires no further key comparisons.


The sorted array is [9,14,18,22,27,31,35,42][9,14,18,22,27,31,35,42], and the final merge uses 6 key comparisons.


c) Find the total number of key comparisons for the entire sort.


Count each merge level separately rather than treating every output item as a comparison.


The four merges of single items each require one comparison, contributing ________. The two merges producing length-four halves each require three comparisons, contributing ________. Part b shows that the final merge requires six comparisons.


Therefore,


Ctotal=4(1)+2(3)+6=4+6+6=16.C_{\text{total}}=4(1)+2(3)+6=4+6+6=16.


As a check, eight items require three merge levels. Their exact comparison counts differ because a merge stops comparing keys as soon as either input is exhausted.


The entire sort uses 16 key comparisons.

A program merges the sorted lists [4,11,16][4,11,16] and [6,9,20][6,9,20] in ascending order. It has already appended 44 and 66. Which item should it append next, and why?

Choose an answer

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A run is a contiguous sorted block. A bottom-up merge sort starts with the array [31,12,27,5,19,8,24,14][31,12,27,5,19,8,24,14], treating each item as a one-item run. Each pass merges adjacent pairs of runs in ascending order.


Complete the table with the runs after each full pass. In each input, enter the integers in order, separated by single spaces, without commas or brackets. A dash marks a position where no separate run remains.

Completed passRun 1Run 2Run 3Run 4
1
2——
3———

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A top-down merge sort arranges [17,6,12,3,15,8,11,2][17,6,12,3,15,8,11,2] in ascending order. It splits each array into equal contiguous halves until single items remain, then performs every merge without an early-order shortcut.


A key comparison compares the current front values of two nonempty inputs. After one input becomes empty, copying the other input's remaining values uses no further key comparisons. Do not count index or loop-condition checks.


How many key comparisons does the entire sort perform? Give an exact integer number of comparisons.

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice