fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. void merge(int arr[], int left, int mid, int right) {
  5. int n1 = mid - left + 1;
  6. int n2 = right - mid;
  7.  
  8. int *L = new int[n1];
  9. int *R = new int[n2];
  10.  
  11. for (int i = 0; i < n1; i++) L[i] = arr[left + i];
  12. for (int j = 0; j < n2; j++) R[j] = arr[mid + 1 + j];
  13.  
  14. int i = 0, j = 0, k = left;
  15.  
  16. while (i < n1 && j < n2) {
  17. if (L[i] <= R[j]) {
  18. arr[k++] = L[i++];
  19. } else {
  20. arr[k++] = R[j++];
  21. }
  22. }
  23.  
  24. while (i < n1) arr[k++] = L[i++];
  25. while (j < n2) arr[k++] = R[j++];
  26.  
  27. delete[] L;
  28. delete[] R;
  29. }
  30.  
  31. void mergeSort(int arr[], int left, int right) {
  32. if (left < right) {
  33. int mid = left + (right - left) / 2;
  34.  
  35. mergeSort(arr, left, mid);
  36. mergeSort(arr, mid + 1, right);
  37.  
  38. merge(arr, left, mid, right);
  39. }
  40. }
  41.  
  42. int main() {
  43. int n;
  44. cin >> n;
  45. int arr[n];
  46. for (int i = 0; i < n; i++) cin >> arr[i];
  47.  
  48. mergeSort(arr, 0, n - 1);
  49.  
  50. for (int i = 0; i < n; i++) cout << arr[i] << " ";
  51. cout << endl;
  52. return 0;
  53. }
Success #stdin #stdout 0.01s 5288KB
stdin
3
2 3 1

stdout
1 2 3