Search Your Query

Breaking

Friday, August 7, 2020

Write A C Program That Merge Two Array In Sorted Order

Merge Two Sorted Array

Code:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. void merge(int *arr,int *brr,int m,int n)
  4. {
  5. int i=0,j=0,k=0;
  6. int *crr;
  7. int l=(n+m);
  8. crr=(int*)malloc(l*sizeof(int));
  9. while(i<n && j<m)
  10. {
  11. crr[k++]=arr[i]<brr[j]?arr[i++]:brr[j++];
  12. }
  13. while(i<n)
  14. {
  15. crr[k++]=arr[i++];
  16. }
  17. while(j<m)
  18. {
  19. crr[k++]=brr[j++];
  20. }
  21. printf("After merging two array\n");
  22. for(k=0;k<l;k++)
  23. {
  24. printf("%d\n",crr[k]);
  25. }
  26. }
  27. int main()
  28. {
  29. int *arr,*brr,m,n,i;
  30. printf("Enter the size of first array\n");
  31. scanf("%d",&n);
  32. arr=(int*)malloc(n*sizeof(int));
  33. printf("Enter the elements of first array\n");
  34. for(i=0;i<n;i++)
  35. {
  36. scanf("%d",&arr[i]);
  37. }
  38. printf("Enter the size of second array\n");
  39. scanf("%d",&m);
  40. brr=(int*)malloc(m*sizeof(int));
  41. printf("enter the elements of second array\n");
  42. for(i=0;i<m;i++)
  43. {
  44. scanf("%d",&brr[i]);
  45. }
  46. printf("First array is-->\n");
  47. for(i=0;i<n;i++)
  48. {
  49. printf("%d\n",arr[i]);
  50. }
  51. printf("Second array-->\n");
  52. for(i=0;i<m;i++)
  53. {
  54. printf("%d\n",brr[i]);
  55. }
  56. merge(arr,brr,m,n);
  57. return 0;
  58. }
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