Created
August 20, 2020 06:46
-
-
Save iamprayush/a4a12b388b5ae75625522e82dee9bfdb to your computer and use it in GitHub Desktop.
Merge 2 sorted arrays with constant space.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Simplest Approach( O(1) extra space without using Insertion Sort) | |
Time Complexity: O(nlogn) => As we sort both the arrays at the end. | |
Space Complexity: O(1) => apart from I/O | |
Procedure/Algo | |
1. | |
Take two pointers , lets call them ptr1 and ptr2. | |
ptr1 runs from end of array1 till the first element. ( endIndex -> 0 ) | |
ptr2 runs from first element of array2 till the last element. (0 -> endIndex ) | |
2. | |
Use a while loop which runs till ptr1 >=0 && ptr2< array2.length | |
2.1 | |
Now swap the elements of array1 and array2 IF (array1 [ptr1] > array2[ptr2] ) | |
(The reason we swap is because all the smaller elements should be in array1 and the larger elements should be in | |
array2.In other words, the largest element of array1 should be lesser than the smallest element of array2) | |
3. | |
Finally sort both array1 and array2 | |
''' | |
for _ in range(int(input())): | |
n, m = map(int,input().split()) | |
arr = input().split() | |
for i in range(n): | |
arr[i] = int(arr[i]) | |
brr = input().split() | |
for i in range(m): | |
brr[i] = int(brr[i]) | |
i, j = n - 1, 0 | |
while i >= 0 and j < m: | |
if arr[i] > brr[j]: | |
arr[i], brr[j] = brr[j], arr[i] | |
j += 1 | |
else: | |
i -= 1 | |
arr.sort() | |
brr.sort() | |
print(*arr, end=" ") | |
print(*brr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment