Advertisement
rotno98

Merge sort

Oct 15th, 2019
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void Merge(int *A,int p,int q,int r)
  6. {
  7. int n1=q-p+1;
  8. int n2=r-q;
  9. int * L=new int[n1]; ///1 base indexing from here
  10. int * R=new int[n2];
  11.  
  12. for(int i=1;i<=n1;i++)
  13. {
  14. L[i]=A[p+i-1];
  15. }
  16.  
  17. for(int j=1;j<=n2;j++)
  18. {
  19. R[j]=A[q+j];
  20. }
  21.  
  22. L[n1+1]=9999999;
  23. R[n2+1]=9999999;
  24.  
  25. int i=1;
  26. int j=1;
  27.  
  28. for(int k=p;k<=r;k++)
  29. {
  30. if(L[i]<=R[j])
  31. {
  32. A[k]=L[i];
  33. i++;
  34. }
  35. else
  36. {
  37. A[k]=R[j];
  38. j++;
  39. }
  40.  
  41. }
  42.  
  43. }
  44.  
  45.  
  46. void Merge_sort(int* A,int p,int r)
  47. {
  48. if(p<r)
  49. {
  50. int q=int((p+r)/2);
  51. Merge_sort(A,p,q);
  52. Merge_sort(A,q+1,r);
  53. Merge(A,p,q,r);
  54. }
  55. }
  56.  
  57. int main()
  58. {
  59.  
  60. int A[]={20,30,10,40,50,5,100,80};
  61. int z=sizeof(A)/sizeof(A[0]);
  62.  
  63.  
  64. Merge_sort(A,0,7);
  65.  
  66. for(int i=0;i<z;i++)
  67. cout<<A[i]<<",";
  68.  
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement