smatskevich

Partition

Apr 5th, 2015
360
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Возвращает индекс опорного элемента. begin и end включительно. begin <= end.
  2. // Опорный - последний.
  3. int Partition( vector<int>& arr, int begin, int end ) {
  4.     assert( begin <= end );
  5.     assert( begin >= 0 && end + 1 <= static_cast<int>( arr.size() ) );
  6.     if( begin == end ) {
  7.         return begin;
  8.     }
  9.     int pivot = arr[end];
  10.     int i = begin;
  11.     int j = end - 1;
  12.     while( i <= j ) {
  13.         // Не проверяем, что i < end, т.к. arr[end] == pivot.
  14.         for( ; arr[i] < pivot; ++i ) {}
  15.         for( ; j >= 0 && arr[j] >= pivot; --j ) {}
  16.         if( i < j ) {
  17.             std::swap( arr[i], arr[j] );
  18.             ++i;
  19.             --j;
  20.         }
  21.     }
  22.     std::swap( arr[i], arr[end] );
  23.     return i;
  24. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×