Skip to main content
Library homepage
Engineering LibreTexts

4.4: Merge Sort

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    Selection sort is a simple algorithm, but it is not very efficient. To sort \(n\) items, it has to traverse the array \(n-1\) times. Each traversal takes an amount of time proportional to \(n\). The total time, therefore, is proportional to \( n^2 \).

    In the next two sections, we’ll develop a more efficient algorithm called merge sort. To sort \(n\) items, merge sort takes time proportional to \(n \log_{2}{n} \). That may not seem impressive, but as \(n\) gets big, the difference between \( n^2 \) and \( n \log_{2}{n} \) can be enormous.

    For example, \( \log_{2} \) of one million is around 20. So if you had to sort a million numbers, selection sort would require one trillion steps; merge sort would require only 20 million.

    The idea behind merge sort is this: if you have two subdecks, each of which has already been sorted, it is easy and fast to merge them into a single, sorted deck. Try this out with a deck of cards:

    1. Form two subdecks with about 10 cards each, and sort them so that when they are face up the lowest cards are on top. Place both decks face up in front of you.
    2. Compare the top card from each deck and choose the lower one. Flip it over and add it to the merged deck.
    3. Repeat step 2 until one of the decks is empty. Then take the remaining cards and add them to the merged deck.

    The result should be a single sorted deck. In the next few sections, we’ll explain how to implement this algorithm in Java.

    This page titled 4.4: Merge Sort is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Allen B. Downey (Green Tea Press) .

    • Was this article helpful?