Advertisement
karbaev

quicksort

Feb 29th, 2016
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. #include <iostream>
  2. #include <stdlib.h>     /* srand, rand */
  3. #include <time.h>       /* time */
  4. using namespace std;
  5. int a[100];
  6. void quickSort(int l, int r){
  7.     srand (time(NULL));
  8.     int x=a[rand() % (r-l+1) + l]; 
  9.     //int x = a[l + (r - l) / 2]; //плохой вариант пивота
  10.     //запись эквивалентна (l+r)/2,
  11.     //но не вызыввает переполнения на больших данных
  12.     int i = l;
  13.     int j = r;
  14.     //код в while обычно выносят в процедуру
  15.     while(i <= j)
  16.     {
  17.         while(a[i] < x) i++;
  18.         while(a[j] > x) j--;
  19.         if(i <= j)
  20.         {
  21.             swap(a[i], a[j]);
  22.             i++;
  23.             j--;
  24.         }
  25.     }
  26.     if (i<r)
  27.         quickSort(i, r);
  28.    
  29.     if (l<j)    
  30.         quickSort(l, j);    
  31. }
  32. int main()
  33. {
  34.     int n;//количество элементов в массиве
  35.     cin >> n;
  36.     for(int i = 0; i < n; i++)
  37.     {
  38.         cin>>a[i];
  39.     }
  40.     quickSort(0, n-1);
  41.     for(int i = 0; i < n; i++)
  42.     {
  43.         cout<<a[i]<<" ";
  44.     }        
  45.     return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement