SHARE
TWEET

merge sort

Mim527 Jun 21st, 2020 (edited) 897 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<stdio.h>
  2.  
  3.  
  4. int main()
  5. {
  6.     int n,i,arr[50];
  7.  
  8.     printf("Enter the size of array\n");
  9.     scanf("%d",&n);
  10.     printf("Enter the elements:");
  11.     for(i=0; i<n; i++)
  12.         scanf("%d",&arr[i]);
  13.  
  14.     mergesort(arr,0,n-1);
  15.  
  16.     printf("Sorted array:");
  17.     for(i=0; i<n; i++)
  18.         printf("\t%d",arr[i]);
  19.  
  20.     return 0;
  21. }
  22.  
  23. void mergesort(int arr[],int low,int high)
  24. {
  25.     int mid;
  26.     if(low<high)
  27.     {
  28.         mid=(low+high)/2;
  29.  
  30.         mergesort(arr,low,mid);
  31.         mergesort(arr,mid+1,high);
  32.         merge(arr,low,mid,high);
  33.     }
  34. }
  35.  
  36. void merge(int arr[],int l,int m,int h)
  37. {
  38.     int arr1[25],arr2[25];
  39.     int n1,n2,i,j,k;
  40.     n1=m-l+1;
  41.     n2=h-m;
  42.  
  43.     for(i=0; i<n1; i++)
  44.         arr1[i]=arr[l+i];
  45.     for(j=0; j<n2; j++)
  46.         arr2[j]=arr[m+j+1];
  47.  
  48.     arr1[i]=9999;
  49.     arr2[j]=9999;
  50.  
  51.     i=0;
  52.     j=0;
  53.  
  54.     for(k=l; k<=h; k++)
  55.     {
  56.         if(arr1[i]<=arr2[j])
  57.         {
  58.             arr[k]=arr1[i];
  59.             i++;
  60.         }
  61.         else
  62.         {
  63.             arr[k]=arr2[j];
  64.             j++;
  65.         }
  66.     }
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top