C Program to Merge Two Arrays Sorted in Descending Order

Ex: Write a C program to merge two arrays and sort in descending order. How to write a C program to merge two arrays and sort in descending order. C program to merge two arrays and sort in descending order.

Input from user:

Enter the limit of first array: 3
Enter elements: 
1
2
3

Enter the limit of second array: 3
Enter elements:
1
2
3

Expected output:

Elements after merged:
3 3 2 2 1 1





  Step by step logic of the given program:


1. Input two arrays size and elements store it in variable say a1, arr1, a2, arr2.

2. Size of 1st array + size of 2nd array = size of merged array so store it in variable a3 using: 
a3=a1+a2;

3. Insert 1st array elements in 3rd array. Run a loop from 0 to a1-1 and store 1st array elements in 3rd array using:

for(i=0;i<a1;i++)
{
arr3[i]=arr1[i];

}
Repeat this process to insert 2nd array elements in 3rd array.

4. To sort the array in descending order use two for loops and inside that use simple swapping logic using (3rd) varible.

5. Print merged and sorted descending order array using:
for(i=0;i<a3;i++)
{
printf("%d ",arr3[i]);

}





  C program to merge two arrays sorted in descending order :


#include<stdio.h>
void main()
{
int arr1[100],arr2[100],arr3[200];
int a1,a2,a3,i,j,temp=0;

/*accept limit of first array*/
printf("Enter the limit of first array:");
scanf("%d",&a1);
/*accept first array elements*/
printf("Enter elements:\n");
for(i=0;i<a1;i++)
{
scanf("%d",&arr1[i]);
}

/*accept limit of second array*/
printf("Enter the limit of second array:");
scanf("%d",&a2);
/*accept second array elements*/
printf("Enter elements:\n");
for(i=0;i<a2;i++)
{
scanf("%d",&arr2[i]);
}
/*size of merged array is size of 1st array and 2nd array*/
a3=a1+a2;

/*insert in the third array*/
  for(i=0;i<a1;i++)
{
arr3[i]=arr1[i];
}

  for(j=0;j<a2;j++)
{
arr3[i]=arr2[j];
i++;
}

/*sort the array in descending order*/
for(i=0;i<a3;i++)
{
for(j=0;j<a3-1;j++)
{
if(arr3[j]<arr3[j+1])
{
temp=arr3[j+1];
arr3[j+1]=arr3[j];
arr3[j]=temp;
}
}
}

/*print the merged array*/
 printf("Elements after merged:\n");
for(i=0;i<a3;i++)
{
printf("%d ",arr3[i]);
}

}


Above program shows the following output:


C program to merge two arrays sorted in descending order, arrays in C, how to write a C program to merge two arrays sorted in descending order

No comments:

Post a Comment

If you have any doubts, please discuss here...👇