A2oz

How to Write a Merge Sort Algorithm?

Published in Algorithm 2 mins read

Merge sort is a highly efficient sorting algorithm that follows the divide-and-conquer approach. Here's how you can write a merge sort algorithm:

Understanding the Algorithm

  1. Divide: Break the unsorted list into two halves.
  2. Conquer: Recursively sort the two halves using merge sort.
  3. Combine: Merge the two sorted halves into a single sorted list.

Implementation

Here's a simple Python implementation of merge sort:

def merge_sort(arr):
  """Sorts an array using the merge sort algorithm."""
  if len(arr) > 1:
    mid = len(arr) // 2
    left_half = arr[:mid]
    right_half = arr[mid:]

    merge_sort(left_half)
    merge_sort(right_half)

    i = j = k = 0
    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

    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

Example

Let's say you have an unsorted array: [8, 3, 1, 7, 0, 10, 2].

  1. Divide: The array is split into two halves: [8, 3, 1, 7] and [0, 10, 2].
  2. Conquer: The merge sort algorithm is recursively applied to each half, resulting in: [1, 3, 7, 8] and [0, 2, 10].
  3. Combine: The two sorted halves are merged, producing the final sorted array: [0, 1, 2, 3, 7, 8, 10].

Advantages of Merge Sort

  • Stable: Maintains the relative order of equal elements.
  • Efficient: Has a time complexity of O(n log n) for both best and average cases.
  • Versatile: Can be used to sort various data types.

Conclusion

Merge sort is a powerful sorting algorithm known for its efficiency and stability. By understanding the divide-and-conquer approach and implementing the algorithm, you can effectively sort arrays of data in a predictable and consistent manner.

Related Articles