Here in this program, we will code to combine two Array in a sorted manner. In this program, we will ask the user to enter elements for two arrays in ascending order and combine both arrays elements and store them in a new array. The new array which would be a union of user two entered arrays must be sorted.
C Program for the Sorted Union of Two Arrays
#include<stdio.h> #include<conio.h> #include<iostream.h> void main() { clrscr(); int a[50],b[50],c[100],k,j,na,nb; cout<<"How many elements you want to enter in Array A and B?\n"; cin>>na>>nb; cout<<"Enter the elements of Array A in ascending order\n"; for(int i=0;i<na;i++) cin>>a[i] ; cout<<"Now Enter elements of Array B in ascending order\n"; for(i=0;i<nb;i++) cin>>b[i]; cout<<"The Union of the two arrays is \n" ; k=0; j=0; for(i=0;i<na+nb;i++) { if(a[k]<b[j]) { c[i] = a[k]; k++; } else if(a[k]>b[j]) { c[i]=b[j]; j++; } else if(k==na) { c[i]=b[j]; j++; } else if(j==nb) { c[i]=a[k]; k++; } } for(i=0;i<na+nb;i++) cout<<c[i]<<" "; getch(); }
Output:
How many elements you want to enter in Array A and B 4 5 Enter the elements of Array A in ascending order 3 4 7 9 Enter the elements of Array B in ascending order 5 8 11 12 16 The Union of the two arrays is 3 4 5 7 8 9 11 12 16
Python Program for the sorted union of two Arrays
a=[] b=[] c=[] na, nb =list(map(int,input("How many elements you want to enter in Array A and B\n").split())) print("Enter the elements of Array A in ascending order") a= [int(input()) for i in range(na)] print("Enter the elements of Array B in ascending order") b=[int(input()) for i in range(nb)] c = sorted(a+b) print("The Union of the two arrays is ") for i in c: print(i,end=" ")
Output: How many elements you want to enter in Array A and B 3 4 Enter the elements of Array A in ascending order 1 5 67 Enter the elements of Array B in ascending order 2 45 50 55 The Union of the two arrays is 1 2 5 45 50 55 67 People are also reading:
- Python Program to Remove Punctuations From a String
- WAP in C to calculate the factorial of a number
- Python Program to Find HCF or GCD
- WAP in C++ & Python to calculate the size of each data types
- Python Program to Check if a Number is Positive, Negative or 0
- WAP in C to check whether the number is a Palindrome number or not
- Python Program to Swap Two Variables
- Write a C++ Calculator to perform Arithmetic Operations using Switch Case
- Python Program to Calculate the Area of a Triangle
- WAP in C++ and python to check whether the number is even or odd
Leave a Comment on this Post