Log In Sign Up
Day 27

Day 27: Mergesort Algorithm

27/60 Days

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.

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 #

  1. Divide the unsorted list into n sublists, each containing one element (a list of one element is considered sorted).
  2. 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):
12    result = []
13    i, j = 0, 0
14    
15    while i < len(left) and j < len( …