What is the Merge Sort in DSA? with Free Explanation

Overview

Merge Sort is a divide-and-conquer algorithm that splits the array into smaller subarrays, sorts them, and then merges them back together. It is an efficient, stable, and comparison-based sorting algorithm.

Key Characteristics

  1. Time Complexity: O(n log n) for all cases (worst, average, and best).
  2. Space Complexity: O(n) due to the temporary arrays used for merging.
  3. Stability: Stable (maintains the relative order of equal elements).
  4. Algorithm Type: Comparison-based, divide-and-conquer sorting.

How Merge Sort Works

  1. Divide: Split the array into two halves.
  2. Conquer: Recursively sort each half.
  3. Combine: Merge the two sorted halves to produce the sorted array.
Merge Sort in DSA

Steps and Example

Consider the following unsorted array:

[5, 3, 8, 4, 2]

Step 1: Divide the array

  • Split [5, 3, 8, 4, 2] into [5, 3, 8] and [4, 2].

Step 2: Recursively sort each half

  • Split [5, 3, 8] into [5, 3] and [8].
  • Split [5, 3] into [5] and [3].

Step 3: Merge sorted halves

  • Merge [5] and [3] to get [3, 5].
  • Merge [3, 5] and [8] to get [3, 5, 8].
  • Split [4, 2] into [4] and [2].
  • Merge [4] and [2] to get [2, 4].
  • Finally, merge [3, 5, 8] and [2, 4] to get [2, 3, 4, 5, 8].

Visualization

Let’s generate a step-by-step visualization of Merge Sort using diagrams:

Initial Array
[5, 3, 8, 4, 2]
Step 1 : Divide
[5, 3, 8, 4, 2]
  /        \
[5, 3, 8]   [4, 2]
Step 2 : Recursively Sort
[5, 3, 8]        [4, 2]
 /     \         /     \
[5, 3] [8]      [4]   [2]
 /  \
[5] [3]
Step 3 : Merge
Merge [5] and [3] -> [3, 5]
Merge [3, 5] and [8] -> [3, 5, 8]
Merge [4] and [2] -> [2, 4]
Merge [3, 5, 8] and [2, 4] -> [2, 3, 4, 5, 8]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top