vadimk772336

Untitled

Oct 8th, 2021
681
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. void merge(int* array, int l, int mid, int r)
  6. {
  7.     int ls = 0, rs = 0;
  8.     int result[r - l + 1];
  9.  
  10.     while ((l + ls < mid + 1) && (mid + rs < r))
  11.     {
  12.         if (array[l + ls] < array[mid + rs + 1])
  13.         {
  14.             result[ls + rs] = array[l + ls];
  15.             ls++;
  16.         }
  17.         else
  18.         {
  19.             result[ls + rs] = array[mid + 1 + rs];
  20.             rs++;
  21.         }
  22.     }
  23.  
  24.     while (l + ls < mid + 1)
  25.     {
  26.         result[ls + rs] = array[l + ls];
  27.         ls++;
  28.     }
  29.  
  30.     while (mid + rs < r)
  31.     {
  32.         result[ls + rs] = array[mid + rs + 1];
  33.         rs++;
  34.     }
  35.  
  36.     for (int i = 0; i < ls + rs; ++i)
  37.         array[l + i] = result[i];
  38. }
  39.  
  40.  
  41. void mergeSort(int* array, int n, int size)
  42. {
  43.     for (int i = size; i < n; i *= 2)
  44.         for (int j = 0; j < n - i; j += 2 * i)
  45.         {
  46.             if (j + 2 * i - 1 > n)
  47.                 merge(array, j, j + i - 1, n);
  48.             else
  49.                 merge(array, j, j + i - 1, j + 2 * i - 1);
  50.         }
  51. }
  52.  
  53. int main()
  54. {
  55.  
  56.     int arr[2000];
  57.     int result[2000];
  58.  
  59.     int count_tests;
  60.     int size, count_mas;
  61.     int arr_size;
  62.  
  63.     ifstream ifs("123.txt");
  64.     ifs >> count_tests;
  65.  
  66.     ofstream out("results.txt");
  67. ;
  68.     for (int i = 0; i < count_tests; ++i)
  69.     {
  70.  
  71.         ifs >> count_mas;
  72.         ifs >> size;
  73.        
  74.         arr_size = count_mas * size;
  75.         for (int j = 0; j < arr_size; ++j)
  76.             ifs >> arr[j];
  77.  
  78.         mergeSort(arr, arr_size, size);
  79.  
  80.         for (int k = 0; k < arr_size; ++k)
  81.         {
  82.             out << arr[k] << ' ';
  83.             arr[k] = 0;
  84.         }
  85.         out << '\n';
  86.        
  87.  
  88.    
  89.     }
  90.     return 0;
  91. }
  92.  
Advertisement
Add Comment
Please, Sign In to add comment