Mim527

merge

Jun 20th, 2020
1,308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.23 KB | None | 0 0
  1. #include<stdio.h>
  2. int arr[20];       // array to be sorted
  3.  
  4. int main()
  5. {
  6.   int n,i;
  7.  
  8.   printf("Enter the size of array\n");  // input the elements
  9.   scanf("%d",&n);
  10.   printf("Enter the elements:");
  11.   for(i=0;i<n;i++)
  12.     scanf("%d",&arr[i]);
  13.  
  14.   merge_sort(arr,0,n-1);  // sort the array
  15.  
  16.   printf("Sorted array:");  // print sorted array
  17.   for(i=0;i<n;i++)
  18.     printf("%d",arr[i]);
  19.  
  20.   return 0;
  21. }
  22.  
  23. int merge_sort(int arr[],int low,int high)
  24. {
  25.   int mid;
  26.   if(low<high)
  27.   {
  28.     mid=(low+high)/2;
  29.    // Divide and Conquer
  30.     merge_sort(arr,low,mid);
  31.     merge_sort(arr,mid+1,high);
  32.    // Combine
  33.     merge(arr,low,mid,high);
  34.   }
  35.  
  36.   return 0;
  37. }
  38.  
  39. int merge(int arr[],int l,int m,int h)
  40. {
  41.   int arr1[10],arr2[10];  // Two temporary arrays to
  42.                              hold the two arrays to be merged
  43.   int n1,n2,i,j,k;
  44.   n1=m-l+1;
  45.   n2=h-m;
  46.  
  47.   for(i=0;i<n1;i++)
  48.     arr1[i]=arr[l+i];
  49.   for(j=0;j<n2;j++)
  50.     arr2[j]=arr[m+j+1];
  51.  
  52.   arr1[i]=9999;  // To mark the end of each temporary array
  53.   arr2[j]=9999;
  54.  
  55.   i=0;j=0;
  56.   for(k=l;k<=h;k++)  //process of combining two sorted arrays
  57.   {
  58.     if(arr1[i]<=arr2[j])
  59.       arr[k]=arr1[i++];
  60.     else
  61.       arr[k]=arr2[j++];
  62.   }
  63.  
  64.   return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment