Advertisement
smatskevich

Seminar9

Nov 14th, 2022
743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <stack>
  3. #include <vector>
  4.  
  5. // Возвращает индекс, где разместится опорный элемент. [l, r)
  6. inline int Partition(std::vector<int>& v, int l, int r) {
  7.   if (r - l <= 1) return 0;
  8.   const int& pivot = v[r - 1];
  9.   int i = l, j = r - 2;
  10.   while (i <= j) {
  11.     // Не проверяем, что i < n - 1, т.к. a[n - 1] == pivot.
  12.     for (; v[i] < pivot; ++i ) {}
  13.     for (; j >= l && !(v[j] < pivot); --j) {}
  14.     if (i < j) std::swap(v[i++], v[j--]);
  15.   }
  16.   std::swap(v[i], v[r - 1]);
  17.   return i;
  18. }
  19.  
  20. /*void foo(int p1, int p2) {
  21.   if (condition) return;
  22.   ...AAA...
  23.   foo(x1, x2);
  24. }
  25. // ...AAA...   ...AAA...  ...AAA...
  26. void foo(int p1, int p2) {
  27.   while (!condition) {
  28.     ...AAA...
  29.     p1 = x1, p2 = x2;
  30.   }
  31. }*/
  32.  
  33. /*void foo(int p1, int p2) {
  34.   //...AA1...
  35.   if (cond1) foo(x1, x2);
  36.   if (cond2) foo(x3, x4);
  37.   if (cond3) foo(x5, x6);
  38. }
  39.  
  40. void foo2() {
  41.   std::stack<std::pair<int, int>> params_stack;
  42.   params_stack.push({0, 100});
  43.   while (!params_stack.empty()) {
  44.     auto param = params_stack.top(); params_stack.pop();
  45.     //...AA1(param)...
  46.     if (cond3) params_stack.push({5, 6});
  47.     if (cond2) params_stack.push({3, 4});
  48.     if (cond1) params_stack.push({1, 2});
  49.   }
  50. }*/
  51.  
  52. // Сортировка на диапазоне [l, r)
  53. void QuickSort(std::vector<int>& v, int l, int r) {
  54.   while (r - l > 1) {
  55.     int pivot_pos = Partition(v, l, r);
  56.     QuickSort(v, l, pivot_pos);
  57.     //QuickSort(v, pivot_pos + 1, r);
  58.     l = pivot_pos + 1;
  59.   }
  60. }
  61.  
  62. void QuickSort(std::vector<int>& v) {
  63.   if (v.size() <= 1) return;
  64.   QuickSort(v, 0, v.size());
  65. }
  66.  
  67. int main() {
  68.   int n = 0;
  69.   std::cin >> n;
  70.   std::vector<int> v(n);
  71.   for (int& x : v) std::cin >> x;
  72.   QuickSort(v);
  73.   for (int x : v) std::cout << x << " ";
  74.   return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement