Code:
- #include<stdio.h>
- #include<stdlib.h>
- void merge(int *arr,int *brr,int m,int n)
- {
- int i=0,j=0,k=0;
- int *crr;
- int l=(n+m);
- crr=(int*)malloc(l*sizeof(int));
- while(i<n && j<m)
- {
- crr[k++]=arr[i]<brr[j]?arr[i++]:brr[j++];
- }
- while(i<n)
- {
- crr[k++]=arr[i++];
- }
- while(j<m)
- {
- crr[k++]=brr[j++];
- }
- printf("After merging two array\n");
- for(k=0;k<l;k++)
- {
- printf("%d\n",crr[k]);
- }
- }
- int main()
- {
- int *arr,*brr,m,n,i;
- printf("Enter the size of first array\n");
- scanf("%d",&n);
- arr=(int*)malloc(n*sizeof(int));
- printf("Enter the elements of first array\n");
- for(i=0;i<n;i++)
- {
- scanf("%d",&arr[i]);
- }
- printf("Enter the size of second array\n");
- scanf("%d",&m);
- brr=(int*)malloc(m*sizeof(int));
- printf("enter the elements of second array\n");
- for(i=0;i<m;i++)
- {
- scanf("%d",&brr[i]);
- }
- printf("First array is-->\n");
- for(i=0;i<n;i++)
- {
- printf("%d\n",arr[i]);
- }
- printf("Second array-->\n");
- for(i=0;i<m;i++)
- {
- printf("%d\n",brr[i]);
- }
- merge(arr,brr,m,n);
- return 0;
- }
Hint: In line 12 we use ternary operator. crr[k++]=arr[i]<brr[j]?arr[i++]:brr[j++]; . This line means if arr[i]<brr[j] is true then this arr[i++] value assign to array crr[k++] and both arr[] and crr[] array increased by 1.If crr[k++]=arr[i]<brr[j] false then this brr[j++] value assign to crr[k++] and both brr[] and crr[] array increased by 1.
Line 16 and 20 means if any value of arr[] or brr[] still can't assigned to crr[] then it will be assigned.
Input:
Enter the size of first array
5
Enter the elements of first array
1
2
3
4
5
Enter the size of second array
5
enter the elements of second array
6
7
8
9
10
First array is-->
1
2
3
4
5
Second array-->
6
7
8
9
10
Output:
After merging two array
1
2
3
4
5
6
7
8
9
10
No comments:
Post a Comment