Merge Sort Algorithm in Python
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.
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:
- Split the unsorted list of values into 2 halves and sort them.
- 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]
:
- Compare 2 from
[2, 4, 5, 7]
with 0 from[0, 1, 3, 6]
, take 0. |[0]
- Compare 2 from
[2, 4, 5, 7]
with 1 from[1, 3, 6]
, take 1. |[0, 1]
- Compare 2 from
[2, 4, 5, 7]
with 3 from[3, 6]
, take 2. |[0, 1, 2]