![]() |
VOOZH | about |
Given an integer array arr[] whose first k elements and remaining n–k elements (for any 0 ≤ k ≤ n) are each sorted, merge these two sorted halves into a single fully sorted array.
Note : There doesn't exists more than two sorted halves in an array.
Examples:
Input : arr[] = [2, 3, 8, -1, 7, 10]
Output : [-1, 2, 3, 7, 8, 10]
Explanation : First and last three sorted elements are [2, 3, 8] and [-1, 7, 10], after merging both halves we get a final sorted array.Input : arr[] = [-4, 6, 9, -1, 3]
Output : [-4, -1, 3, 6, 9]
Explanation : First three and last two sorted elements are [-4, 6, 9] and [-1, 3], after merging both halves we get a final sorted array.
Table of Content
The main logic is to sort the array using built in functions (generally an implementation of quick sort). This approach ignores the “two halves” and simply calls the language’s built‑in sort to sort the entire array.
-1 2 3 7 8 10
Time Complexity : O(n(log(n)))
Auxiliary Space : O(log(n))
Note :- For Java, Python and C# the Space Complexity will be O(n)
The main idea behind this approachis to use an auxiliary array which is very similar to the Merge Function of Merge sort. Find where the first sorted part ends, then walk through both parts side by side, always picking the smaller next number to build the fully sorted list.
-1 2 3 7 8 10