Write a program which input natural number N and M followed by integer arrays A[] and B[], each consisting of N and M number of elements respectively. Sort the arrays A[] and B[] in descending order of magnitude. Use the sorted arrays to generate a merged array C[]. Array C[] should be generated in descending order. Assume that input arrays comprise maximum 20 elements each, with no duplicates. Common elements should be included in the merged array only once. The output format is as follows:-Write a program which input natural number N and M followed by integer arrays A[] and B[], each consisting of N and M number of elements respectively. Sort the arrays A[] and B[] in descending order of magnitude. Use the sorted arrays to generate a merged array C[]. Array C[] should be generated in descending order. Assume that input arrays comprise maximum 20 elements each, with no duplicates. Common elements should be included in the merged array only once. The output format is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
import java.util.*; public class ISC2001 { Scanner sc = new Scanner(System.in); void sort(int a[], int s) { int i, j, tmp; for(i=0;i<s;i++) { //The function sorts any int array in descending order for(j=0;j<s-1-i;j++) { if(a[j]<a[j+1]) { tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } } void input(int a[]) { int i; for(i=0;i<a.length;i++) { a[i] = sc.nextInt(); } } void run() { int a[], b[], c[], i, j, N, M, k=0, f; System.out.println("Enter the size of the two arrays: "); N = sc.nextInt(); M = sc.nextInt(); a = new int[N]; b = new int[M]; c = new int[M+N]; System.out.println("Enter the values for the first array: "); input(a); System.out.println("Enter the values for the second array: "); input(b); sort(a, N); sort(b, M); for(i=0;i<N;i++) { //transfering all values from first array to third array c[i] = a[i]; } k=N; for(i=0;i<M;i++) { f=1; for(j=0;j<N;j++) { if(b[i] == a[j]) { f = 0; break; } } if(f==1) { //transferring values from B only when they are not found in a c[k] = b[i]; k++; } } sort(c, k); System.out.println("Merged Array: "); for(i=0;i<k;i++) { System.out.println(c[i]); } } public static void main() { ISC2001 ob = new ISC2001(); ob.run(); } } |

OUTPUT:

## Leave a Reply