Merge Sort

Merge Sort Algorithm

Key Takeaways: Merge Sort is one of the most efficient sorting algorithms. It uses a "Divide and Conquer" approach, splitting the array in half until it cannot be split anymore, and then merging those pieces back together in sorted order.

Like Quick Sort, Merge Sort is extremely fast and is widely used in real-world programming. In fact, many programming languages (like Java) use a variation of Merge Sort for their built-in sorting functions!

Let's explore how it divides data to conquer massive sorting problems.


1. The Divide and Conquer Approach

Merge Sort literally cuts the problem in half over and over again.

The algorithm follows two main steps:

  1. Divide: Keep cutting the array in half until you are left with arrays that only have 1 element each. (An array with 1 element is already perfectly sorted!)
  2. Conquer (Merge): Pair up these 1-element arrays and merge them into a 2-element sorted array. Pair up the 2-element arrays into 4-element sorted arrays. Repeat until the whole array is rebuilt!
Visual representation of Merge Sort dividing and conquering

Merge Sort: Splitting down to single elements, then merging them back in perfect order.


2. A Step-by-Step Example

Let's trace how Merge Sort handles this array: [38, 27, 43, 3]

Phase 1: Divide (Splitting)

Phase 2: Conquer (Merging)


3. Merge Sort Code Example

Below is the Python implementation of Merge Sort. It uses Recursion (a function calling itself) to continuously split the array, and a helper loop to merge the arrays back together.

Merge Sort in Python

def merge_sort(arr):
    if len(arr) > 1:
        # Find the middle point
        mid = len(arr) // 2
        # Divide the array elements
        left_half = arr[:mid]
        right_half = arr[mid:]
        # Recursively sort both halves
        merge_sort(left_half)
        merge_sort(right_half)
        # Conquer: Merge the sorted halves
        i = j = k = 0
        # Compare elements from left and right halves
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1
        # Check if any elements were left over
        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1
        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1
    return arr

numbers = [38, 27, 43, 3, 9, 82, 10] print("Original:", numbers) print("Sorted:", merge_sort(numbers))


4. Time and Space Complexity


Exercise 1 of 1

?

In Merge Sort, when does the algorithm stop dividing (splitting) an array?