Skip to content
Home » Merge sort

Merge sort

Sure 👍
Here is a detailed, MCA exam-oriented discussion on Merge Sort with analysis of running time, written in a clear, structured, and scoring format.


📘 Merge Sort (with Running Time Analysis)

1️⃣ Introduction

Merge Sort is a Divide-and-Conquer sorting algorithm.

🔹 Idea

  • Divide the array into two halves
  • Recursively sort both halves
  • Merge the sorted halves

It is one of the most efficient sorting algorithms with guaranteed O(n log n) time.


2️⃣ Working Principle (Divide & Conquer)

🔹 Steps

  1. Divide: Split array into two halves
  2. Conquer: Recursively sort both halves
  3. Combine: Merge the sorted halves

3️⃣ Algorithm (Merge Sort)

🔹 Pseudocode

MergeSort(A, low, high):
   if low < high:
       mid = (low + high) / 2
       MergeSort(A, low, mid)
       MergeSort(A, mid+1, high)
       Merge(A, low, mid, high)

🔹 Merge Function

Merge(A, low, mid, high):
   create temporary arrays L and R

   copy elements into L and R

   i = 0, j = 0, k = low

   while i < size(L) and j < size(R):
       if L[i] <= R[j]:
           A[k] = L[i]
           i++
       else:
           A[k] = R[j]
           j++
       k++

   copy remaining elements

4️⃣ Example (Step-by-Step)

🔹 Given Array:

A = [38, 27, 43, 3, 9, 82, 10]

🔹 Step 1: Divide

[38,27,43,3]   [9,82,10]

🔹 Step 2: Further Divide

[38,27] [43,3]   [9,82] [10]

🔹 Step 3: Merge

[27,38] [3,43] → [3,27,38,43]
[9,82] [10] → [9,10,82]

🔹 Final Merge

[3,27,38,43] + [9,10,82]
→ [3,9,10,27,38,43,82]

✔ Sorted array


5️⃣ Running Time Analysis

🔹 Recurrence Relation

[
T(n) = 2T(n/2) + O(n)
]

Where:

  • 2T(n/2) → sorting two halves
  • O(n) → merging

🔹 Using Master Theorem

[
T(n) = O(n \log n)
]


6️⃣ Time Complexity

CaseComplexity
Best CaseO(n log n)
Average CaseO(n log n)
Worst CaseO(n log n)

✔ Same complexity in all cases


7️⃣ Space Complexity

  • O(n) (extra space for merging)
  • Not in-place

8️⃣ Recursion Tree Analysis (Concept)

  • Number of levels = log n
  • Work per level = n

Total work:
[
n \times \log n = O(n \log n)
]


9️⃣ Characteristics of Merge Sort

✔ Stable sorting algorithm
✔ Guaranteed performance
✔ Works well for large data
✖ Requires extra memory


🔟 Advantages

  • Efficient for large datasets
  • Predictable performance
  • Suitable for linked lists
  • Used in external sorting

1️⃣1️⃣ Disadvantages

  • Requires extra memory
  • Slower than Quick Sort in practice
  • Not in-place

1️⃣2️⃣ Comparison with Other Algorithms

AlgorithmTime ComplexitySpace
Merge SortO(n log n)O(n)
Quick SortO(n log n) avgO(log n)
Bubble SortO(n²)O(1)

🔚 Conclusion

Merge Sort is a powerful and efficient sorting algorithm based on divide-and-conquer, with guaranteed O(n log n) performance.

Its strength lies in consistent performance, making it ideal for large datasets.


📌 Exam Tip

👉 Always include:

  • Divide–Conquer steps
  • Recurrence relation
  • Time complexity
  • Example