Python Program for Merge Sort
Intermediate · Searching and sorting
Merge sort is a divide and conquer algorithm: it splits the list in half, sorts each half the same way, and then merges the two sorted halves into one sorted list. Splitting stops at lists of one element, which are already sorted. This program prints every merge, indented by how deep the split is.
Program
Original list: [38, 27, 43, 3, 9, 82]
Merge [27] and [43] -> [27, 43]
Merge [38] and [27, 43] -> [27, 38, 43]
Merge [9] and [82] -> [9, 82]
Merge [3] and [9, 82] -> [3, 9, 82]
Merge [27, 38, 43] and [3, 9, 82] -> [3, 9, 27, 38, 43, 82]
Sorted list: [3, 9, 27, 38, 43, 82]How it works
- The function splits the list at
midand calls itself on each half, until every piece has one element. - The
whileloop merges two sorted halves by comparing their front items and taking the smaller one each time. - When one half runs out, whatever is left in the other is already sorted, so it is added on the end.
- The deepest merges print first and with the most indentation, and the last line is the final merge of the two big halves.
- Merge sort always takes about n x log n steps, much faster than bubble sort on big lists, and
<=keeps equal items in their original order.
Another way to write it
Bottom-up, without recursion
Start: [[38], [27], [43], [3], [9], [82], [10]] Merged: [[27, 38], [3, 43], [9, 82], [10]] Merged: [[3, 27, 38, 43], [9, 10, 82]] Merged: [[3, 9, 10, 27, 38, 43, 82]] Sorted list: [3, 9, 10, 27, 38, 43, 82]
Start with one-item lists and merge neighbours in pairs, round after round, until one list is left. heapq.merge() does the merging of two sorted lists.
Try it yourself
Add a counter that counts how many comparisons the merges make, and compare it with bubble sort on the same list.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises