Advertisement
Guest User

Листики

a guest
Oct 22nd, 2014
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. //Vladislav Orlov
  2. //23.10.2014
  3. //подсчет листьев в быстрой сортировке
  4.  
  5. #include <iostream>
  6. #include <ctime>
  7.  
  8. using namespace std;
  9.  
  10. void quickSort(int arr[], int left, int right);
  11. void results(int arr[]);
  12.  
  13. int pet = 0; //листики
  14.  
  15. int main()
  16. {
  17.     srand(time(0));
  18.    
  19.     int n = 10;
  20.     int* a = new int[n];
  21.  
  22.     cout << "Before: ";
  23.     for (int i=0; i<n;i++)
  24.     {
  25.         a[i] = rand()%100;
  26.         cout << a[i] << " ";
  27.     }
  28.     cout << endl << "After: ";
  29.     quickSort(a, 0, n-1);
  30.     for (int i=0; i<n;i++)
  31.     {
  32.         cout << a[i] << " ";
  33.     }
  34.     cout << endl << "Petals: "<< pet << endl;
  35.     return 0;
  36. }
  37.  
  38. void quickSort(int arr[], int left, int right) {
  39.     bool isPet = true; //считаем что мы листик
  40.     pet++; //увеличиваем количество                                           
  41.    
  42.  
  43.     int i = left, j = right;
  44.     int tmp;
  45.     int pivot = arr[(left + right) / 2];
  46.  
  47.     while (i <= j) {
  48.         while (arr[i] < pivot)
  49.                 i++;
  50.         while (arr[j] > pivot)
  51.                 j--;
  52.         if (i <= j) {
  53.                 tmp = arr[i];
  54.                 arr[i] = arr[j];
  55.                 arr[j] = tmp;
  56.                 i++;
  57.                 j--;
  58.         }
  59.     };
  60.  
  61.     if (left < j)
  62.     {
  63.         quickSort(arr, left, j);        //оказывается мы не листик :(
  64.         pet--;                          //удаляем себя из листиков
  65.         isPet = false;                  //мы больше не листик
  66.     }
  67.     if (i < right)
  68.     {
  69.         if (isPet)                      //защита от повторного удаления
  70.         {
  71.             pet--;
  72.             isPet = false;
  73.         }
  74.         quickSort(arr, i, right);
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement