Sorting and Order Statistics - Merge Sort

Merge Sort: Sorting and Order Statistics

Merge Sort: Sorting and Order Statistics

Merge Sort is a widely used sorting algorithm known for its efficiency and stability. It falls under the category of divide and conquer algorithms, which involves breaking down a problem into smaller subproblems until they are simple enough to solve. Merge Sort operates by recursively dividing the input array into halves, sorting each half, and then merging the sorted halves to produce a fully sorted array.

Algorithm Overview:

The merge sort algorithm can be summarized in the following steps:

  1. Divide the unsorted array into two halves.
  2. Recursively sort each half.
  3. Merge the two sorted halves into a single sorted array.

Key Features:

  • Efficiency: Merge Sort has a time complexity of O(n log n), making it highly efficient even for large datasets.
  • Stability: Merge Sort is a stable sorting algorithm, meaning it preserves the relative order of equal elements in the sorted output.
  • Divide and Conquer: Its divide and conquer approach ensures optimal performance by breaking down the sorting problem into smaller, manageable subproblems.

Implementation:

Below is a high-level implementation of the Merge Sort algorithm in Python:


def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2
    left_half = merge_sort(arr[:mid])
    right_half = merge_sort(arr[mid:])
    return merge(left_half, right_half)

def merge(left, right):
    result = []
    left_idx, right_idx = 0, 0
    
    while left_idx < len(left) and right_idx < len(right):
        if left[left_idx] < right[right_idx]:
            result.append(left[left_idx])
            left_idx += 1
        else:
            result.append(right[right_idx])
            right_idx += 1

    result.extend(left[left_idx:])
    result.extend(right[right_idx:])
    return result

# Example usage:
arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_arr = merge_sort(arr)
print(sorted_arr)
  

This implementation recursively divides the input array into halves and merges them back together in sorted order.

Conclusion:

Merge Sort is a powerful algorithm for sorting and order statistics, providing efficiency, stability, and scalability. Its divide and conquer strategy makes it suitable for a wide range of applications where sorting is required.