Advertisement
STANAANDREY

quicksort

Sep 17th, 2020
1,016
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int partition(int a[], int l, int r) {
  5.     int pivot = a[r];
  6.     int i = l - 1;
  7.     for (int j = l; j < r; j++) {
  8.         if (a[j] <= pivot) {
  9.             i++;
  10.             swap(a[i], a[j]);
  11.         }
  12.     }
  13.     swap(a[i + 1], a[r]);
  14.     return i + 1;
  15. }
  16.  
  17. void quicksort(int a[], int l, int r) {
  18.     if (l < r) {
  19.         int pivot = partition(a, l, r);
  20.         quicksort(a, l, pivot - 1);
  21.         quicksort(a, pivot + 1, r);
  22.     }
  23. }
  24.  
  25.  
  26.  
  27. int a[] = {20, 3, 2, 1, 4, 0, 9, -1};
  28. int main () {
  29.     quicksort(a, 1, 7);
  30.     for (int i = 1; i <= 7; i++)
  31.         std::cerr << a[i] << '\n';
  32.     return 0;
  33. }
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement