Merge Sorted Descending

The program must accept two lines of integers (M and N number of integers) which are sorted in ascending order. The program must merge the two lines of integers such that the merged integers are sorted in descending order. Finally, the program must print the merged integers as the output.

Boundary Condition(s):
1 <= M, N <= 10^5

Input Format:
The first line contains M and N separated by a space.
The second line contains M integers separated by a space.
The third line contains N integers separated by a space.

Output Format:
The first line contains M + N integers separated by a space.

Example Input/Output 1:
Input:
4 6
13 15 17 28
1 7 14 23 25 26

Output:
28 26 25 23 17 15 14 13 7 1

Example Input/Output 2:
Input:
5 3
8 10 13 23 40
9 32 39

Output:
40 39 32 23 13 10 9 8

import java.io.*;
import java.util.*;
public class Main {
int[] mergeSortedDescending(int[] a, int[] b, int n, int m) {
int[] arr = new int[n + m];
int i = n - 1;
int j = m - 1;
int k = m + n - 1;
while (i >= 0 && j >= 0) {
if (a[i] > b[j]) {
arr[k--] = a[i--];
} else {
arr[k--] = b[j--];
}
}
while (j >= 0) {
arr[k--] = b[j--];
}
while (i >= 0) {
arr[k--] = a[i--];
}

return arr;
}
public static void main(String[] args) {
Main obj = new Main();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=sc.nextInt();
int a[]=new int[n];
        for(int i=0;i<n;i++)a[i]=sc.nextInt();
        int b[]=new int[m];
        for(int i=0;i<m;i++)b[i]=sc.nextInt();
int[] result = obj.mergeSortedDescending(a, b, a.length, b.length);
 for (int i = result.length-1; i >= 0; i--) {
            System.out.print(result[i] + " ");
        }

}
}
Previous Article

Two Integers Plus or Minus

Next Article

Same Bits - Odd Positions

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *