Merge sort Algorithm - AOA module 3
Divide and Conquer Approach
The Divide and Conquer approach is a problem-solving strategy that breaks a problem into smaller subproblems, solves them independently, and then combines their solutions to get the final result.
Steps in Divide and Conquer Approach:
- Divide: The problem is divided into smaller subproblems of the same type.
- Conquer: The subproblems are solved recursively (or directly if they are small enough).
- Combine: The solutions of the subproblems are merged to get the final solution.
Examples of Divide and Conquer Algorithms:
- Merge Sort
- Quick Sort
- Binary Search
- Strassen’s Matrix Multiplication
Merge Sort
Definition
Merge Sort is a sorting algorithm based on the divide and conquer strategy. It recursively divides an array into two halves, sorts them individually, and then merges them to form a sorted array.
Steps in Merge Sort:
- Divide: Split the array into two equal (or almost equal) halves.
- Conquer: Recursively sort each half.
- Combine: Merge the two sorted halves into a single sorted array.
Functionality (Working of Merge Sort)
1. If the array has one or zero elements, it is already sorted.
2. Recursively split the array into two halves until single-element arrays are obtained.
3. Merge the sorted halves back together by comparing elements and placing them in order.
Example
Consider an array: [38, 27, 43, 3, 9, 82, 10]
Step-by-step breakdown:
- Divide: [38, 27, 43, 3] and [9, 82, 10]
- Further divide into smaller parts: [38, 27], [43, 3], [9, 82], [10]
- Keep dividing until single-element arrays: [38] [27] [43] [3] [9] [82] [10]
- Sort and Merge:
- Merge [38] and [27] → [27, 38]
- Merge [43] and [3] → [3, 43]
- Merge [9] and [82] → [9, 82]
- [10] remains as it is.
- Merge [27, 38] and [3, 43] → [3, 27, 38, 43]
- Merge [9, 82] and [10] → [9, 10, 82]
- Merge the final two sorted halves → Final Sorted Array: [3, 9, 10, 27, 38, 43, 82]
Advantages of Merge Sort
- Stable Sort: Maintains the relative order of equal elements.
- Guaranteed O(n log n) Time Complexity: Performs consistently well compared to Quick Sort in worst cases.
- Good for Linked Lists: Works efficiently with linked lists since it does not require random access.
- Parallelizable: Can be optimized using multi-threading.
Disadvantages of Merge Sort
- Uses Extra Space: Requires O(n) additional memory for merging.
- Slower for Small Datasets: Overhead of recursive calls makes it inefficient for small arrays.
- Not In-Place: Needs additional memory, unlike Quick Sort which sorts in place.
Comments
Post a Comment