Merge Sort
🌟 Merge Sort
Merge Sort is a Divide and Conquer algorithm.
-
It divides the array into two halves,
-
Sorts each half recursively,
-
And then merges the two sorted halves into one sorted array.
Main idea:
👉 Break the problem into smaller pieces, solve them individually, then combine the solutions.
📜 Merge Sort Algorithm:
-
Divide the array into two halves.
-
Recursively sort the left and right halves.
-
Merge the sorted halves.
Algorithm Steps
MergeSort(A, left, right):
-
If left >= right, return (base case: array of 1 element is already sorted)
-
Find the middle point
mid = (left + right)/2
-
Call MergeSort(A, left, mid)
-
Call MergeSort(A, mid+1, right)
-
Call Merge(A, left, mid, right)
Merge(A, left, mid, right):
-
Create two temporary arrays:
-
Left half → A[left...mid]
-
Right half → A[mid+1...right]
-
-
Compare elements of two arrays one by one, and copy the smaller one into the original array.
-
Copy any remaining elements.
📚 Example:
Suppose the array is: [38, 27, 43, 3, 9, 82, 10]
-
Split → [38, 27, 43, 3] and [9, 82, 10]
-
Split further → [38, 27] and [43, 3]
-
Split → [38] and [27] (single element, sorted)
-
Merge → [27, 38]
-
Split [43] and [3], Merge → [3, 43]
-
Merge → [27, 38, 3, 43] → after sorting → [3, 27, 38, 43]
-
Similarly for [9, 82, 10] → merge sorted → [9, 10, 82]
-
Finally merge → [3, 9, 10, 27, 38, 43, 82]
Sorted array: [3, 9, 10, 27, 38, 43, 82]
🧠Important Points
-
Time complexity: O(n log n) in all cases (best, average, worst).
-
Space complexity: O(n) extra space needed (for temporary arrays).
-
Merge Sort is Stable and efficient for large data sets (does not change the order of equal elements).
Comments
Post a Comment