Merge Sort Algorithm in Python

Better Everything
9 min readMar 27, 2023

Using the merge sort algorithm is an efficient way to sort an unsorted list of values. It is called merge sort because it splits the unsorted list in two, sorts the halves and merges them back together to a list of values sorted from small to big.

Learn how to code the merge sort algorithm in Python.
Learn how to code the merge sort algorithm in Python. Image by catalyststuff on Freepik

In Python you can just use the sorted function to easily sort a list. But in this article we will code the merge sort algorithm as a practice to better understand how it works.

How does the merge sort algorithm work?

The 2 main steps of the merge sort algorithm are:

  1. Split the unsorted list of values into 2 halves and sort them.
  2. Merge the sorted halves back together.

If we would take the list [7, 2, 5, 4, 1, 6, 0, 3] as an example, the halves would be [7, 2, 5, 4] and [1, 6, 0, 3].

If we assume that these halves will be sorted they can be merged back together to also get a sorted end result.

This is how the merging works for the example of [2, 4, 5, 7] and [0, 1, 3, 6]:

  1. Compare 2 from [2, 4, 5, 7] with 0 from [0, 1, 3, 6], take 0. | [0]
  2. Compare 2 from [2, 4, 5, 7] with 1 from [1, 3, 6], take 1. | [0, 1]
  3. Compare 2 from [2, 4, 5, 7] with 3 from [3, 6], take 2. | [0, 1, 2]

--

--

Better Everything

📖 My E-Books: amazon.com/author/better-everything ✅Programming, Data & Business ✅Automation & Optimization ✅Knowledge & Inspiration