fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. // A function to merge the two half into a sorted data.
  6. void Merge(int *a, int low, int high, int mid)
  7. {
  8. // We have low to mid and mid+1 to high already sorted.
  9. int i, j, k, temp[high-low+1];
  10. i = low;
  11. k = 0;
  12. j = mid + 1;
  13.  
  14. // Merge the two parts into temp[].
  15. while (i <= mid && j <= high)
  16. {
  17. if (a[i] < a[j])
  18. {
  19. temp[k] = a[i];
  20. k++;
  21. i++;
  22. }
  23. else
  24. {
  25. temp[k] = a[j];
  26. k++;
  27. j++;
  28. }
  29. }
  30.  
  31. // Insert all the remaining values from i to mid into temp[].
  32. while (i <= mid)
  33. {
  34. temp[k] = a[i];
  35. k++;
  36. i++;
  37. }
  38.  
  39. // Insert all the remaining values from j to high into temp[].
  40. while (j <= high)
  41. {
  42. temp[k] = a[j];
  43. k++;
  44. j++;
  45. }
  46.  
  47.  
  48. // Assign sorted data stored in temp[] to a[].
  49. for (i = low; i <= high; i++)
  50. {
  51. a[i] = temp[i-low];
  52. }
  53. }
  54.  
  55. // A function to split array into two parts.
  56. void MergeSort(int *a, int low, int high)
  57. {
  58. int mid;
  59. if (low < high)
  60. {
  61. mid=(low+high)/2;
  62. // Split the data into two half.
  63. MergeSort(a, low, mid);
  64. MergeSort(a, mid+1, high);
  65.  
  66. // Merge them to get sorted output.
  67. Merge(a, low, high, mid);
  68. }
  69. }
  70.  
  71. int main()
  72. {
  73. int n, i;
  74. n = 1000000;
  75.  
  76. int arr[n];
  77. for(i = 0; i < n; i++)
  78. {
  79. arr[i] = rand();
  80. }
  81.  
  82. MergeSort(arr, 0, n-1);
  83.  
  84. // Printing the sorted data.
  85. cout<<"\nSorted Data ";
  86. for (i = 0; i < n; i++)
  87. cout<<arr[i]<<"\n";
  88.  
  89. return 0;
  90. }
Success #stdin #stdout 0.01s 5516KB
stdin
Standard input is empty
stdout
Sorted Data 35005211
42999170
84353895
135497281
137806862
149798315
184803526
233665123
278722862
294702567
304089172
336465782
356426808
412776091
424238335
468703135
491705403
511702305
521595368
572660336
596516649
608413784
610515434
628175011
635723058
709393584
719885386
749241873
752392754
756898537
760313750
783368690
805750846
846930886
855636226
859484421
861021530
939819582
943947739
945117276
982906996
1025202362
1059961393
1100661313
1101513929
1102520059
1125898167
1129566413
1131176229
1141616124
1159126505
1189641421
1264095060
1303455736
1315634022
1350490027
1365180540
1369133069
1374344043
1411549676
1424268980
1433925857
1469348094
1474612399
1477171087
1540383426
1548233367
1585990364
1632621729
1649760492
1653377373
1656478042
1681692777
1714636915
1726956429
1734575198
1749698586
1780695788
1801979802
1804289383
1827336327
1843993368
1889947178
1911759956
1914544919
1918502651
1937477084
1956297539
1957747793
1967513926
1973594324
1984210012
1998898814
2001100545
2038664370
2044897763
2053999932
2084420925
2089018456
2145174067