C program Write a function that integrates or merges two uns
C program
Write a function that integrates or merges two unsorted strings into sorted order. You will need to provide multiple solutions.
i. Solution 1: Merge items into a third, fixed-sized array.
ii. Solution 2: Merge items into a third, dynamically allocated array, which grows as each item is inserted.
iii. Solution 3: Merge items without the use of a third array.
Solution
Code:
#include <stdio.h>
void Merge(int * , int , int , int );
void MergeSort(int *array, int left, int right){
int mid = (left+right)/2;
if(left<right){
MergeSort(array,left,mid);
MergeSort(array,mid+1,right);
Merge(array,left,mid,right);
}
}
void Merge(int *array, int left, int mid, int right){
int tempArray[right-left+1];
int pos=0,lpos = left,rpos = mid + 1;
while(lpos <= mid && rpos <= right){
if(array[lpos] < array[rpos]){
tempArray[pos++] = array[lpos++];
}else{
tempArray[pos++] = array[rpos++];
}
}
while(lpos <= mid) tempArray[pos++] = array[lpos++];
while(rpos <= right)tempArray[pos++] = array[rpos++];
int iter;
for(iter = 0;iter < pos; iter++){
array[iter+left] = tempArray[iter];
}
return;
}
main(){
int arr1 [10], arr2 [10], arr3 [20];
int i, n1, n2, m, index=0;
printf(\"\ Enter the number of elements in array 1: \");
scanf(\"%d\", &n1);
printf(\"\ Enter the Elements of the first array\ \");
for(i=0;i<n1;i++){
scanf (\"%d\",&arr1[i]);
}
printf(\"\ Enter the number of elements in array 2: \");
scanf (\"%d\", &n2 );
printf(\"\ Enter the Elements of the second array\ \");
for(i=0;i<n2;i++){
scanf (\"%d\", &arr2[i]);
m = n1+n2;
}
for(i=0;i<n1;i++){
arr3[index]=arr1[i];
index++;
}
for(i=0;i<n2;i++){
arr3[index]=arr2[i];
index++;
}
MergeSort(arr3, 0, m-1);
printf (\"\ \ The merged array is:\ \");
for(i=0;i<m;i++){
printf(\"\\t\ Arr[%d] = %d\", i, arr3[i]);
}
return 0;
}
Output:

