Searching and sorting · Algorithm 3 of 15
Merge Sort
Split a sequence, sort its halves, and merge in linear time. Citation needed
The whole, before the parts
Merge sort orders a collection by splitting it into smaller collections, sorting those, and combining their results. The key connection is that combining two ordered lists is simpler than sorting an arbitrary list. Citation needed
Terminology and core concepts
Divide and conquer means solving smaller copies of a problem and combining their answers. Merge sort stops at lists of length zero or one, sorts each half recursively, and merges them. During a merge, the smallest remaining value must be at the front of one of the two sorted halves. Choosing that value preserves the sorted output prefix. This version returns a new list and leaves the input unchanged. Citation needed
Learning path
Trace an example
[8, 3, 5, 1] split [8, 3] [5, 1] split [8] [3] [5] [1] merge [3, 8] [1, 5] merge [1, 3, 5, 8]
Implement it in Python
Read the loop alongside the trace, then run this self-contained example with Python 3. The assertions show expected results. Inputs use ordinary Python lists and dictionaries; comparisons and numeric operations are assumed to behave normally. Citation needed
def merge_sort(values):
if len(values) <= 1:
return values[:]
mid = len(values) // 2
left = merge_sort(values[:mid])
right = merge_sort(values[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
assert merge_sort([8, 3, 5, 1]) == [1, 3, 5, 8]
assert merge_sort([]) == []
assert merge_sort([2, 2, 1]) == [1, 2, 2]Citation needed
Analyze the cost
Every level does O(n) splitting and merging work, and there are O(log n) levels: O(n log n) time in best and worst cases for this implementation. Peak extra storage is O(n), including slices and merge output; recursive depth is O(log n). Taking the left item on ties makes it stable. Citation needed
A mistake to watch for
Using pop(0) on Python lists shifts the rest of the list each time and can destroy the linear merge bound. Use indices. Citation needed
Practice and recall
-
Merge [2, 7] with [3, 6]. How many comparisons are needed?
Work it out before opening the solution. Citation needed
Show the reasoning
- Compare 2 and 3: take 2.
- Compare 7 and 3: take 3.
- Compare 7 and 6: take 6; then append 7. Three comparisons produce [2, 3, 6, 7].
Citation needed
- Why can the merge compare only the two front values?
- Each remaining half is already sorted. Citation needed
To check your understanding, reproduce the implementation without looking, explain why its main step is safe, and test an edge case before moving to the next algorithm. Citation needed
Sources
- MIT OpenCourseWare: Introduction to Algorithms — lecture notes — further study of the underlying algorithm and analysis.
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein, Introduction to Algorithms — correctness arguments and complexity analysis.