Introduction
We are going to know how we can merge the two sorted arrays given to us and sort the merged array but in descending order. Let's assume we have array1 with n number of elements and array 2 with m number of elements in it. Our desired output is to have an array 3 with n+m number of elements of both of the given array, and this array three should be sorted in descending order with efficient time complexity.
Approach-1
We are going to learn two approaches to how we can handle this problem. In this first approach, we will sort the array in descending order by selecting one element at a time and will iterate over the rest of the elements and start comparing with them until we find an element greater than that and swap the positions of those elements. We will loop over this logic until the array is sorted.
Algorithm
- Declare the size of arrays.
- Take input of size of arrays.
- Initialize array1 and array2.
- Copy the elements of the first array to the merged array when initializing it.
- Copy the elements of the second array to the merged array while initializing the second array.
- Sort the merged array.
- Display the array result.
Implementation
#include <stdio.h>
int main() {
/*Array Size Declaration*/
int size1, size2, size3;
printf("\nEnter the size for the first array: ");
scanf("%d", & size1);
printf("\nEnter the size for the second array: ");
scanf("%d", & size2);
size3 = size1 + size2;
printf("\nEnter the elements in a sorted manner:");
/*Array Declaration*/
int array1[size1], array2[size2], array3[size3];
/*Array Initialized*/
for (int i = 0; i < size1; i++) {
scanf("%d", & array1[i]);
array3[i] = array1[i];
}
int k = size1;
printf("\nEnter the elements in a sorted manner:");
/*Array Initialized*/
for (int i = 0; i < size2; i++) {
scanf("%d", & array2[i]);
array3[k] = array2[i];
k++;
}
printf("\nmerged array of first and second:\n");
for (int i = 0; i < size3; i++)
/*Printing the merged array*/
printf("%d ", array3[i]);
printf("\nsorted array in descending order\n");
/*Sorting Array*/
for (int i = 0; i < size3; i++) {
int temp;
for (int j = i + 1; j < size3; j++) {
if (array3[i] < array3[j]) {
temp = array3[i];
array3[i] = array3[j];
array3[j] = temp;
}
}
}
/*Printing the sorted Array*/
for (int i = 0; i < size3; i++) {
printf(" %d ", array3[i]);
}
return 0;
}
Output
Complexity Analysis
Time complexity: O((n+m)2), where n and m are the sizes of the first and second array respectively.
Space complexity: O(n+m)