fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. void mergeSort(vector<int> &arr)
  6. {
  7. if (arr.size() > 1)
  8. {
  9. int mid = arr.size() / 2;
  10.  
  11. vector<int> L (arr.begin(), arr.begin() + mid);
  12. vector<int> R (arr.begin() + mid, arr.end());
  13.  
  14.  
  15. //for(auto x: L) cout<<x<<" ";
  16. //cout<<"\n";
  17. //for(auto x: R) cout<<x<<" ";
  18. //cout<<"\n";
  19.  
  20. mergeSort(L);
  21. mergeSort(R);
  22.  
  23. int i = 0, j = 0, k = 0;
  24.  
  25. while ( i < L.size() and j < R.size())
  26. {
  27. if (L[i] < R[j])
  28. {
  29. arr[k] = L[i];
  30. i++;
  31. }
  32. else
  33. {
  34. arr[k] = R[j];
  35. j++;
  36. }
  37. k++;
  38. }
  39.  
  40. while (i < L.size())
  41. {
  42. arr[k] = L[i];
  43. i++;
  44. k++;
  45. }
  46. while (j < R.size())
  47. {
  48. arr[k] = R[j];
  49. j++;
  50. k++;
  51. }
  52. }
  53. }
  54.  
  55. int main(){
  56. vector<int> arr({12, 11, 13, 5, 6, 7});
  57. //cout<<"Given array is : ";
  58. //for(auto x: arr) cout<<x<<" ";
  59. mergeSort(arr);
  60. cout<<"\nSorted array is : ";
  61. for(auto x: arr) cout<<x<<" ";
  62. }
Success #stdin #stdout 0s 4412KB
stdin
Standard input is empty
stdout
Sorted array is : 5 6 7 11 12 13