fork download
  1. #include <iostream>
  2. #include <ctime>
  3. using namespace std;
  4.  
  5. void Merge(int A[], int L[], int R[], int nA, int nL, int nR) {
  6. int i = 0, j = 0, k = 0;
  7. while (i < nL && j < nR) {
  8. if (L[i] < R[j]) {
  9. A[k] = L[i];
  10. i++;
  11. } else {
  12. A[k] = R[j];
  13. j++;
  14. }
  15. k++;
  16. }
  17. while (i < nL) {
  18. A[k] = L[i];
  19. i++;
  20. k++;
  21. }
  22. while (j < nR) {
  23. A[k] = R[j];
  24. j++;
  25. k++;
  26. }
  27. }
  28.  
  29. void Merge_sort(int A[], int n) {
  30. if (n < 2) return;
  31.  
  32. int mid = n / 2;
  33. int v1 = mid, v2 = n - mid;
  34. int left[v1], right[v2];
  35.  
  36. for (int i = 0; i < mid; i++) {
  37. left[i] = A[i];
  38. }
  39. for (int i = mid; i < n; i++) {
  40. right[i - mid] = A[i];
  41. }
  42.  
  43. Merge_sort(left, mid);
  44. Merge_sort(right, n - mid);
  45. Merge(A, left, right, n, mid, n - mid);
  46. }
  47.  
  48. int main() {
  49. int n, i;
  50. cout << "Enter the size of the array: ";
  51. cin >> n;
  52. int A[n];
  53. cout << "Enter the elements: ";
  54. for (i = 0; i < n; i++) {
  55. cin >> A[i];
  56. }
  57.  
  58. clock_t start = clock();
  59. Merge_sort(A, n);
  60. clock_t end = clock();
  61.  
  62. cout << "Sorted array: ";
  63. for (i = 0; i < n; i++) {
  64. cout << A[i] << " ";
  65. }
  66. cout << endl;
  67.  
  68.  
  69. double time_taken = double(end - start) / CLOCKS_PER_SEC * 1000;
  70. cout << "Time taken to sort the array: " << time_taken << " ms" << endl;
  71.  
  72. return 0;
  73. }
  74.  
Success #stdin #stdout 0s 5284KB
stdin
5
1 2 3 4 5
stdout
Enter the size of the array: Enter the elements: Sorted array: 1 2 3 4 5 
Time taken to sort the array: 0 ms