Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.22 KB | None | 0 0
  1. //------------------------------------------------------------------------------------
  2. //Selects the element to be used for dividing. Moves all the smaller elements
  3. //to the left of this element, and greater than or equal to the right
  4. /*  Type *_arr <- pointer at the beginning of the array
  5.     int _left  <- the number of the first element of the left part of the array
  6.     int _right <- the number of the last element of the right part of the array
  7.     bool _ascending <- variable that determines the sorting method
  8.  
  9.     if _ascending == true: sorting in ascending order
  10.     if _ascending == false: sorting in descending order
  11. */
  12. template <typename Type>
  13. int separate(Type *_arr,int _left,int _right,bool _ascending){
  14.     int x = _arr[_left]; // obieramy pivot
  15.     int i = _left, j = _right, w; // i, j - indeksy w tabeli
  16.     while (true) // petla nieskonczona - wychodzimy z niej tylko przez return j
  17.     {
  18.         switch((int)_ascending){
  19.             case true: //sorting in ascending order
  20.                 while (_arr[j] > x) // dopoki elementy sa wieksze od x
  21.                     j--;
  22.                 while (_arr[i] < x) // dopoki elementy sa mniejsze od x
  23.                     i++;
  24.                 if (i < j) // zamieniamy miejscami gdy i < j
  25.                 {
  26.                     w = _arr[i];
  27.                     _arr[i] = _arr[j];
  28.                     _arr[j] = w;
  29.                     i++;
  30.                     j--;
  31.                 }
  32.                 else // gdy i >= j zwracamy j jako punkt podzialu tablicy
  33.                     return j;
  34.                 break;
  35.                
  36.             case false: //sorting in descending order
  37.                 while (_arr[j] < x) // dopoki elementy sa wieksze od x
  38.                     j--;
  39.                 while (_arr[i] > x) // dopoki elementy sa mniejsze od x
  40.                     i++;
  41.                 if (i < j) // zamieniamy miejscami gdy i < j
  42.                 {
  43.                     w = _arr[i];
  44.                     _arr[i] = _arr[j];
  45.                     _arr[j] = w;
  46.                     i++;
  47.                     j--;
  48.                 }
  49.                 else // gdy i >= j zwracamy j jako punkt podzialu tablicy
  50.                     return j;
  51.                 break;
  52.         }
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement