Given an array of size n, the task is to sort the given array using iterative merge sort.
Examples:
Input: arr[] = [4, 1, 3, 9, 7]
Output: [1, 3, 4, 7, 9]
Explanation: The output array is sorted.
Input: arr[] = [1, 3 , 2]
Output: [1, 2, 3]
Explanation: The output array is sorted.
Please refer Merge Sort for typical recursive solution.
Approach:
The idea is to implement an iterative merge sort that avoids recursion by taking a bottom-up approach, starting with individual elements and progressively merging sorted subarrays of increasing sizes (1, 2, 4, 8...), where at each level we pair adjacent subarrays and merge them until the entire array is sorted.
Detailed Explanation:
- In traditional recursive merge sort, we use a top-down approach where we keep dividing the array until we reach individual elements. However, this requires maintaining a function call stack and involves overhead from function calls.
- The iterative version eliminates this overhead by working bottom-up. We start by considering each element as a sorted subarray of size 1. Then in each pass, we merge adjacent pairs of these sorted subarrays to create larger sorted subarrays.
- The outer loop controls the size of subarrays being merged (currSize), which doubles in each iteration (1, 2, 4, 8...). For each size, we iterate through the array to find pairs of adjacent subarrays to merge.
- A key insight is handling array sizes that aren't powers of 2. For example, with 7 elements, when merging size-2 subarrays, we might have pairs like (2,2,2,1). The algorithm handles this by using the min function to correctly calculate the endpoints of subarrays.
Time complexity: O(n * log n)
Space Complexity: O(n)