In: Computer Science
. Escriba un programa en C para combinar dos arreglos del mismo tamaño ordenadas en orden decendiente. Datos de prueba : Introduzca el número de elementos que se almacenarán en el primer arreglo :3 Entrada 3 elementos en el arreglo: elemento[0]: 1 elemento[1]: 2 elemento[2]: 3 Introduzca el número de elementos que se almacenarán en el segundo arreglo :3 Entrada 3 elementos en el arreglo: elemento[0]: 1 elemento[1]: 2 elemento[2]: 3
Program
#include <stdio.h>
#define MAX_SIZE 100 // Maximum size of the array
int main()
{
int arr1[MAX_SIZE], arr2[MAX_SIZE], mergeArray[MAX_SIZE * 2];
int size1, size2, mergeSize;
int index1, index2, mergeIndex;
int i;
/* Input size of first array */
printf("Enter the number of items to be stored in the first array:
: ");
scanf("%d", &size1);
/* Input elements in first array */
printf("Input %d items into the array: ",size1);
for(i=0; i<size1; i++)
{
printf("\nItem [%d] : ",i);
scanf("%d", &arr1[i]);
}
/* Input size of second array */
printf("\nEnter the number of items to be stored in the second
array: : ");
scanf("%d", &size2);
/* Input elements in second array */
printf("Input %d items into the array: ",size2);
for(i=0; i<size2; i++)
{
printf("\nItem [%d] : ",i);
scanf("%d", &arr2[i]);
}
mergeSize = size1 + size2;
/*
* Merge two array in descending order
*/
index1 = 0;
index2 = 0;
for(mergeIndex=0; mergeIndex < mergeSize; mergeIndex++)
{
/*
* If all elements of one array
* is merged to final array
*/
if(index1 >= size1 || index2 >= size2)
{
break;
}
if(arr1[index1] > arr2[index2])
{
mergeArray[mergeIndex] = arr1[index1];
index1++;
}
else
{
mergeArray[mergeIndex] = arr2[index2];
index2++;
}
}
/*
* Merge remaining array elements
*/
while(index1 < size1)
{
mergeArray[mergeIndex] = arr1[index1];
mergeIndex++;
index1++;
}
while(index2 < size2)
{
mergeArray[mergeIndex] = arr2[index2];
mergeIndex++;
index2++;
}
/*
* Print merged array
*/
printf("\nArray merged in ascending order : ");
for(i=0; i<mergeSize; i++)
{
printf("%d\t", mergeArray[i]);
}
printf("\n");
return 0;
}
Output
Enter the number of items to be stored in the first array: :
3
Input 3 items into the array:
Item [0] : 3
Item [1] : 2
Item [2] : 1
Enter the number of items to be stored in the second array: :
3
Input 3 items into the array:
Item [0] : 6
Item [1] : 5
Item [2] : 4
Array merged in ascending order : 6 5
4 3 2 1