Merge Sort
Table of Contents
Merge Sort
Merge sort follows the divide and conquer paradigm.
For mergesort
- We break the array into two subarrays to be sorted and then combine the ordered subarrays to make the whole ordered array;
- We do the two recursive calls before working on the whole array;
- The array is divided in half;
Pros
- Mergesort guarantees to sort an array of N items in time proportional to N log N, no matter what the input.
Cons
- Its prime disadvantage is that it uses extra space proportional to N.
Example
Example: Sorting [38, 27, 43, 3, 9, 82, 10]
Let’s walk through sorting the array [38, 27, 43, 3, 9, 82, 10] using merge sort.
- Divide:
- Split array into [38, 27, 43] and [3, 9, 82, 10].
- Split [38, 27, 43] into [38] and [27, 43].
- Split [27, 43] into [27] and [43].
- Split [3, 9, 82, 10] into [3, 9] and [82, 10].
- Split [3, 9] into [3] and [9].
- Split [82, 10] into [82] and [10].
- Conquer (Merge):
- Merge [27] and [43] → [27, 43].
- Merge [38] and [27, 43] → [27, 38, 43].
- Merge [3] and [9] → [3, 9].
- Merge [82] and [10] → [10, 82].
- Merge [3, 9] and [10, 82] → [3, 9, 10, 82].
- Merge [27, 38, 43] and [3, 9, 10, 82] → Compare and merge:
- L = [27, 38, 43], R = [3, 9, 10, 82]
- Compare 27 vs 3 → Pick 3
- Compare 27 vs 9 → Pick 9
- Compare 27 vs 10 → Pick 10
- Compare 27 vs 82 → Pick 27
- Compare 38 vs 82 → Pick 38
- Compare 43 vs 82 → Pick 43
- Take 82
- Final array: [3, 9, 10, 27, 38, 43, 82]
Steps of the Merge Method
- Input: The merge method takes two sorted subarrays (or arrays) as input. For example, if the original array is [4, 7, 2, 5], it might be divided into two sorted subarrays: [4, 7] and [2, 5].
- Create a Temporary Array: A temporary array is created to store the merged result. This ensures the original array isn’t overwritten prematurely.
- Compare and Merge:
- Two pointers (e.g., i and j) are used to track the current elements in the first and second subarrays, respectively.
- Compare the elements at i and j:
- If the element in the first subarray (arr[i]) is smaller or equal, copy it to the temporary array and increment i.
- Otherwise, copy the element from the second subarray (arr[j]) and increment j.
- Move the temporary array’s index forward after each copy.
- Continue until one subarray is exhausted.
- Copy Remaining Elements:
- If any elements remain in the first subarray (i.e., i hasn’t reached the end), copy them to the temporary array.
- Similarly, copy any remaining elements from the second subarray.
- Copy Back to Original Array: Transfer the sorted elements from the temporary array back to the original array in the appropriate range.
Complexity analysis
- Time Complexity: O(n log n) for all cases.
- Space Complexity: O(n) for temporary arrays during merging.
- Stable: Maintains relative order of equal elements.
- Use Case: Efficient for large datasets, especially linked lists, but requires extra space.