Day 27: Mergesort Algorithm
Mergesort Algorithm#
Welcome to Day 27 of our 60 Days of Coding Algorithm Challenge! Today, we’ll dive deep into the Mergesort algorithm, another efficient and widely used sorting algorithm based on the divide-and-conquer paradigm.
See it in motion: watch merge sort divide and merge 100 values in sorted waves in our free interactive visualizer.
Introduction to Mergesort#
Mergesort is a comparison-based sorting algorithm that follows the divide-and-conquer approach. It divides the input array into two halves, recursively sorts them, and then merges the two sorted halves.
How Mergesort Works#
- Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted).
- Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list.
Basic Implementation of Mergesort#
Here’s a basic implementation of the Mergesort algorithm:
1def merge_sort(arr):
2 if len(arr) <= 1:
3 return arr
4
5 mid = len(arr) // 2
6 left = merge_sort(arr[:mid])
7 right = merge_sort(arr[mid:])
8
9 return merge(left, right)
10
11def merge(left, right): …Keep your momentum going
Create a free account to unlock the full lesson, all 60 days, and track your progress as you go.
- Full access to all 60 daily lessons
- Track completion and build a daily streak
- Get interview-ready, one algorithm at a time
Join 2,900+ learners · 4.8/5 average rating