fork download
  1. // Online C++ compiler to run C++ program online
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. void merge(vector<int>&v,int l,int mid,int r)
  5. {
  6. vector<int>temp;
  7.  
  8.  
  9. int x=l;
  10. int x1=mid+1;
  11. while(x<=mid&&x1<=r)
  12. {
  13. if(v[x]<=v[x1])
  14. {
  15. temp.push_back(v[x]);
  16. x++;
  17.  
  18. }
  19. else
  20. {
  21. temp.push_back(v[x1]);
  22. x1++;
  23.  
  24. }
  25. }
  26. while(x<=mid)
  27. {
  28. temp.push_back(v[x]);
  29. x++;
  30.  
  31. }while(x1<=r)
  32. {
  33. temp.push_back(v[x1]);
  34. x1++;
  35.  
  36. }
  37. for(int k=0;k<temp.size();k++)
  38. {
  39. v[l+k]=temp[k];
  40.  
  41. }
  42.  
  43.  
  44.  
  45. }
  46. void mergesort(vector<int>&v,int l,int r)
  47. {
  48. if(l<r)
  49. {
  50. int mid=l+(r-l)/2;
  51. mergesort(v,l,mid);
  52. mergesort(v,mid+1,r);
  53. merge(v,l,mid,r);
  54.  
  55. }
  56. }
  57.  
  58.  
  59. // Write C++ code here
  60. //std::cout << "Try programiz.pro";
  61. int main()
  62. {
  63. vector<int>v={8,9,3,2,7,1,5};
  64. cout<<"unsorted array is :"<<endl;
  65.  
  66. for(auto k:v)
  67. {
  68. cout<<k<<" ";
  69.  
  70. }
  71. mergesort(v,0,v.size()-1);
  72. cout<<"the sorted array is:"<<endl;
  73. for(auto l:v)
  74. {
  75. cout<<l<<" ";
  76.  
  77. }
  78. }
  79.  
  80.  
  81.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
unsorted array is :
8 9 3 2 7 1 5 the sorted array is:
1 2 3 5 7 8 9