Advertisement
Korotkodul

QuickSort_AGAIN_OK

Oct 2nd, 2023 (edited)
584
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <cmath>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using std::cin;
  6. using std::cout;
  7. using std::max;
  8. using std::min;
  9. using std::string;
  10. using std::vector;
  11.  
  12. void Swap(int* p1, int* p2) {
  13.   int tt = *p1;
  14.   *p1 = *p2;
  15.   *p2 = tt;
  16. }
  17.  
  18. vector<int> ar;
  19.  
  20. void Partition(int low, int high, int xnum) {
  21.   // делим на < и >=
  22.   int lft = low - 1;
  23.   for (int id = low; id <= high; ++id) {
  24.     if (ar[id] < xnum) {
  25.       int* p1 = &ar[id];
  26.       int* p2 = &ar[lft + 1];
  27.       Swap(p1, p2);
  28.       lft++;
  29.     }
  30.   }
  31.   // делим на = и >
  32.   for (int id = lft + 1; id <= high; ++id) {
  33.     if (ar[id] == xnum) {
  34.       int* p1 = &ar[id];
  35.       int* p2 = &ar[lft + 1];
  36.       Swap(p1, p2);
  37.       lft++;
  38.     }
  39.   }
  40. }
  41.  
  42. void QuickSort(int low, int high) {
  43.   if (low >= high) {
  44.     return;
  45.   }
  46.   int piv = ar[low];
  47.   Partition(low, high, piv);
  48.   int lft = low;
  49.   while (ar[lft] != piv) {
  50.     lft++;
  51.   }
  52.   int rgt = high;
  53.   while (ar[rgt] != piv) {
  54.     rgt--;
  55.   }
  56.   // lft - самый левый piv
  57.   // rgt - самый правый piv
  58.   QuickSort(low, lft - 1);
  59.   QuickSort(rgt + 1, high);
  60. }
  61.  
  62. int main() {
  63.   std::ios::sync_with_stdio(false);
  64.   std::cin.tie(0);
  65.   std::cout.tie(0);
  66.   int len;
  67.   cin >> len;
  68.   ar.resize(len);
  69.   for (int& el : ar) {
  70.     cin >> el;
  71.   }
  72.   // Partition(0, len - 1, 5);
  73.   QuickSort(0, len - 1);
  74.   for (int el : ar) {
  75.     cout << el << ' ';
  76.   }
  77. }
  78. /*
  79. 17
  80. 2 2 0 2 1 2 0 2 1 0 2 1 2 2 0 0 2
  81.  
  82. 16
  83. 7 10 3 4 5 11 2 1 2 3 1 5 4 6 7 1
  84. */
  85.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement