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.
-
Conquer- Recursively sort the left and right halves.
-
Combine-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:
[38, 27, 43, 3, 9, 82, 10]
We start by dividing it into two halves:
Left: [38, 27, 43, 3]
Right: [9, 82, 10]
🔹 Step 3: Divide Left Half [38, 27, 43, 3]
[38, 27] and [43, 3]
Now divide again:
[38] [27] and [43] [3]
Merge and sort each pair:
[38] + [27] → [27, 38]
[43] + [3] → [3, 43]
Now merge these two sorted subarrays:
[27, 38] + [3, 43] → [3, 27, 38, 43]
✅ Left half sorted: [3, 27, 38, 43]
🔹 Step 4: Divide Right Half [9, 82, 10]
[9] and [82, 10]
Split [82, 10]:
[82] [10] → merge → [10, 82]
Now merge with [9]:
[9] + [10, 82] → [9, 10, 82]
✅ Right half sorted: [9, 10, 82]
🔹 Step 5: Final Merge
Now merge the two sorted halves:
Left: [3, 27, 38, 43]
Right: [9, 10, 82]
📚 Example:merge
Explanation
-
Divide phase (top-down):
-
The array is split recursively until each subarray has only one element.
-
-
Conquer phase (bottom-up):
-
Adjacent subarrays are merged in sorted order.
-
-
Final result:
-
The sorted array is built step by step through merging.
Merge Sort Tree Visualization
🧠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