Advertisement
allia

слияние

Oct 12th, 2020 (edited)
1,762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.14 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. void merge_series (int *arr, int first, int last_1, int last_2, int *dubl)
  7. {
  8.   int i = first;
  9.   int j = last_1+1;
  10.   int c = 0;
  11.  
  12.  for (c = first; c <= last_2; c++)
  13.   if (j > last_2)
  14.     dubl[c] = arr[i++];
  15.      else if (i > last_1)
  16.       dubl[c] = arr[j++];
  17.       else if (arr[i] <= arr[j])
  18.        dubl[c] = arr[i++];
  19.        else dubl[c] = arr[j++];
  20. }
  21.  
  22. void sort (int *arr, int first, int last, int *dubl)
  23. {
  24.   int middle = (first + last)/2;
  25.  
  26.   if (first < middle)
  27.    sort (arr, first, middle, dubl);
  28.   if (middle + 1 < last)
  29.    sort (arr, middle+1, last, dubl);
  30.  
  31.   merge_series (arr, first, middle, last, dubl);
  32.  
  33.  
  34.   for (int i = first; i <= last; i++)
  35.    {
  36.      arr[i] = dubl[i];
  37.      //cout << dubl[i] << " ";
  38.    }
  39.    //cout << endl;
  40. }
  41.  
  42. void merge_sort (int *arr, int razmer)
  43. {
  44.   int *dubl = new int[razmer];
  45.   sort (arr, 0, razmer-1, dubl);
  46. }
  47.  
  48. int main()
  49. {
  50.   int n=0;
  51.   cin >> n;
  52.  
  53.   int *arr = new int[n];
  54.   for (int i=0; i<n; i++)
  55.    cin >> arr[i];
  56.  
  57.   merge_sort (arr, n);
  58.  
  59.   for (int i=0; i<n; i++)
  60.    cout << arr[i] << " ";
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement