Introduction
Merge Sortis a robust, comparison-
based sorting algorithm. It
fundamental strategy is to break
down a problem into smaller sub-
problems, solving each recursively.
It strictly follows the Divide and
Conquer approach.
Time Complexity: O(n log n) in all
cases (Worst, Average, and Best).
Space Complexity: O(n) due to the
requirement of temporary arrays for
merging.
3.
Working Principle
Divide:
Continuouslysplit the array into two
equal halves until they can no longer be
divided.
Conquer:
Recursively sort the sub-arrays. (Single
elements are naturally sorted).
Combine:
Merge the two sorted sub-arrays back
into a single sorted array.
4.
Algorithm Steps
BaseCase Check: If the array has 0 or 1 element, it is
considered already sorted. Return immediately.
Recursive Division: Find the middle index and divide the array
into two halves (Left and Right).
Sort Halves: Recursively call Merge Sort for the first half and
then for the second half.
Merge: Compare elements from both sorted halves and merge
them into a new, fully sorted array.
Pseudo Code:
MergeSort
MERGE-SORT(arr, left,
right)
IFleft < right THEN
mid = (left + right) / 2
MERGE-SORT(arr,
left, mid)
MERGE-SORT(arr,
mid + 1, right)
MERGE(arr, left, mid,
right)
Pseudo Code: Merge
MERGE(arr, left, mid, right)
n1 = mid - left + 1
n2 = right - mid
Create arrays L[1..n1], R[1..n2]
Copy elements of arr[left..mid] into L
Copy elements of arr[mid+1..right] into R
i = 0, j = 0, k = left
WHILE i < n1 AND j < n2
IF L[i] <= R[j]
arr[k] = L[i]
i = i + 1
ELSE
arr[k] = R[j]
j = j + 1
k = k + 1
Copy remaining elements of L (if any)
Copy remaining elements of R (if any)
7.
Applications and Conclusion
Merge Sort is a powerful divide and
conquer algorithm
Provides consistent O(n log n)
performance
Preferred when stability and
efficiency are required
Sorting linked lists
External sorting (large files)
Used in databases and file
systems