Merge sort in Python
Merge sort splits the list in half, sorts each half the same way, then merges the two sorted halves by always taking the smaller front value. This version merges back into the original list, so you can watch the bars settle.
The arrow keys step through it. Edit the code to try your own input.
How it works
merge_sort(nums, start, end)sorts the part of the list fromstartup to, but not including,end.- A part with one value is already sorted, so the function returns at once. That is the base case.
- Otherwise it splits at
midand sorts the left half, then the right half, each with its own recursive call. - It copies both sorted halves into
leftandright, then writes the smaller front value intonums[k]again and again. - When one half runs out, the rest of the other half is copied in, already in order.
What to watch
- Watch the call stack: calls go deeper until each part holds one value, and the merging happens on the way back up.
- Watch
kmove right through the part being merged while its bars are rewritten in sorted order. - Watch
iandj: they point into the copiesleftandright, not intonums.
The code
def merge_sort(nums, start, end): if end - start <= 1: return # one value is already sorted mid = (start + end) // 2 merge_sort(nums, start, mid) # sort the left half merge_sort(nums, mid, end) # sort the right half left, right = nums[start:mid], nums[mid:end] i = j = 0 k = start while i < len(left) and j < len(right): if left[i] <= right[j]: nums[k] = left[i] i += 1 else: nums[k] = right[j] j += 1 k += 1 for value in left[i:] + right[j:]: # copy what is left over nums[k] = value k += 1 data = [6, 3, 8, 1, 5, 2] merge_sort(data, 0, len(data)) print(data)
Output
[1, 2, 3, 5, 6, 8]
Open it in the editor · Python Program for Merge Sort, explained