ArticleslgStudy

computer science

Merge sort

Merge sort is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Merge sort rather than just read about it. In short: Merge sort (also commonly spelled as mergesort or merge-sort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations of merge sort are stable, which means that the relative order of equal elements is the same between the input and output.

Merge sort — main illustration
Merge sort — illustration

Key takeaways

  • Merge sort belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Merge sort to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Merge sort from memory before moving on to harder problems.

Reference excerpt

Merge sort (also commonly spelled as mergesort or merge-sort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations of merge sort are stable, which means that the relative order of equal elements is the same between the input and output. Merge sort is a divide-and-conquer algorithm that was invented by John von Neumann in 1945. A detailed description and analysis of bottom-up merge sort appeared in a report by Goldstine and von Neumann as early as 1948.

Algorithm Conceptually, a merge sort works as follows:

Divide the unsorted list into n sub-lists, each containing one element (a list of one element is considered sorted). Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list. Merge sort is efficient because merging and sorting two sublists can be performed in linear time, provided that the sublists are already sorted.

Top-down implementation Example C-like code using indices for top-down merge sort algorithm that recursively splits the list into sublists (called runs in this example) until sublist size is 1, then merges those sublists to produce a sorted list. The copy back step is avoided with alternating the direction of the merge with each level of recursion (except for an initial one-time copy, that can be avoided too). As a simple example, consider an array with two elements. The elements are copied to b, then merged back to a. If there are four elements, when the bottom of the recursion level is reached, single element runs from a are merged to b, and then at the next higher level of recursion, those two-element runs are merged to a. This pattern continues with each level of recursion.

Sorting the entire array is accomplished by topDownMergeSort(a, b, a.length).

Bottom-up implementation Example C-like code using indices for bottom-up merge sort algorithm which treats the list as an array of n sublists (called runs in this example) of size 1, and iteratively merges sub-lists back and forth between two buffers:

Top-down implementation using lists Pseudocode for top-down merge sort algorithm which recursively divides the input list into smaller sublists until the sublists are trivially sorted, and then merges the sublists while returning up the call chain.

function merge_sort(list m) is // Base case. A list of zero or one elements is sorted, by definition. if length of m ≤ 1 then return m

// Recursive case. First, divide the list into equal-sized sublists // consisting of the first half and second half of the list. // This assumes lists start at index 0. var left := empty list var right := empty list for each x with index i in m do if i < (length of m)/2 then add x to left else add x to right

// Recursively sort both sublists. left := merge_sort(left) right := merge_sort(right)

// Then merge the now-sorted sublists. return merge(left, right)

In this example, the merge function merges the left and right sublists.

function merge(left, right) is var result := empty list

while left is not empty and right is not empty do if first(left) ≤ first(right) then append first(left) to result left := rest(left) else append first(right) to result right := rest(right)

// Either left or right may have elements left; consume them. // (Only one of the following loops will actually be entered.) while left is not empty do append first(left) to result left := rest(left) while right is not empty do append first(right) to result right := rest(right) return result

Bottom-up implementation using lists Pseudocode for bottom-up merge sort algorithm which uses a small fixed size array of references to nodes, where array[i] is either a reference to a list of size 2i or nil. node is a reference or pointer to a node. The merge() function would be similar to the one shown in the top-down merge lists example, it merges two already sorted lists, and handles empty lists. In this case, merge() would use node for its input parameters and return value.

function merge_sort(node head) is // return if empty list if head = nil then return nil var node array[32]; initially all nil var node result var node next var int i result := head // merge nodes into array while result ≠ nil do next := result.next; result.next := nil for (i = 0; (i < 32) && (array[i] ≠ nil); i += 1) do result := merge(array[i], result) array[i] := nil // do not go past end of array if i = 32 then i -= 1 array[i] := result result := next // merge array into single list result := nil for (i = 0; i < 32; i += 1) do result := merge(array[i], result) return result

Top-down implementation in a declarative style Haskell-like pseudocode, showing how merge sort can be implemented in such a language using constructs and ideas from functional programming.

Analysis

… excerpt ends here. Continue reading the full article.

Illustrations

Merge sort illustration
Merge sort: A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).
A recursive merge sort algorithm used to sort an array of 7 integer values. These are the steps a human would take to emulate merge sort (top-down).
Merge sort: Merge sort type algorithms allowed large data sets to be sorted on early computers that had small random access memories by modern standards. Records were stored on magnetic tape and processed on banks of magnetic tape drives, such as these IBM 729s.
Merge sort type algorithms allowed large data sets to be sorted on early computers that had small random access memories by modern standards. Records were stored on magnetic tape and processed on banks of magnetic tape drives, such as these IBM 729s.
Merge sort: Tiled merge sort applied to an array of random integers.  The horizontal axis is the array index and the vertical axis is the integer.
Tiled merge sort applied to an array of random integers. The horizontal axis is the array index and the vertical axis is the integer.
Merge sort: The parallel multiway mergesort process on four processors 
  
    
      
        
          t
          
            0
          
        
      
    
    {\displaystyle t_{0}}
  
 to 
  
    
      
        
          t
          
            3
          
        
      
    
    {\displaystyle t_{3}}
  
.
The parallel multiway mergesort process on four processors t 0 {\displaystyle t_{0}} to t 3 {\displaystyle t_{3}} .

Worked examples

Example 1 — a first encounter with Merge sort

Start with the simplest possible case. Write down what Merge sort claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Merge sort before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Merge sort ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Merge sort

In research
Merge sort appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Merge sort in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Merge sort is common in secondary-school and first-year university syllabi. It links to neighbouring topics Comparison sorts, Divide-and-conquer algorithms, Stable sorts, so understanding it makes those chapters shorter.
In everyday life
Look for Merge sort outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.

Affiliate

Preply — study more efficiently by working with a personal tutor. 50% off.

How to study Merge sort in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Merge sort means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Merge sort out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Merge sort in simple terms?

Merge sort (also commonly spelled as mergesort or merge-sort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations of merge sort are stable, which means that the relative order of equal elements is the same between the input and output.

Why does Merge sort matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Merge sort?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Merge sort.

Tags

  • Comparison sorts
  • Divide-and-conquer algorithms
  • Stable sorts

Keep exploring