In [ ]:
%%HTML
<style>
.container { width:100% }
</style>
In order to sort a list $L$ using merge sort we proceed as follows:
\mathtt{merge}\bigl(\mathtt{sort}\bigl(\texttt{L[:n//2]}\bigr),
\mathtt{sort}\bigl(\texttt{L[n//2:]}\bigr)\bigr)
$$
Here, $\texttt{L[:n//2]}$ is the first part of the list, while
$\texttt{L[n//2:]}$ is the second part. If the length of $L$ is even, both part have the same number of elements, otherwise the second part has one element more than the first part.
In [ ]:
def sort(L):
n = len(L)
if n < 2:
return L
L1, L2 = L[:n//2], L[n//2:]
return merge(sort(L1), sort(L2))
We still need to specify how two sorted lists $L_1$ and $L_2$ are merged in a way that the resulting list is also sorted.
In [ ]:
def merge(L1, L2):
if L1 == []:
return L2
if L2 == []:
return L1
x1, R1 = L1[0], L1[1:]
x2, R2 = L2[0], L2[1:]
if x1 <= x2:
return [x1] + merge(R1, L2)
else:
return [x2] + merge(L1, R2)
In [ ]:
sort([7, 8, 11, 12, 2, 5, 3, 7, 9, 3, 2])
In [ ]: