avr39ripe

cppSortStatisticsMinBuble

Jul 30th, 2021 (edited)
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     enum Methods { bubleSort, minSort, Count };
  6.     const int randBegin{ 10 };
  7.     const int randEnd{ 99 };
  8.     const int testsCount{ 10 };
  9.     const int arrSize{ 1000 };
  10.  
  11.     int arr[arrSize];
  12.     int premutation[Methods::Count]{};
  13.     int copy{};
  14.     int noPremutation{true};
  15.     int min{ 0 };
  16.  
  17.     srand(time(0));
  18.  
  19.     for (int testNum{}; testNum < testsCount; ++testNum)
  20.     {
  21.         // buble Sort
  22.         for (int i{ 0 }; i < arrSize; ++i) { arr[i] = randBegin + (rand() % (randEnd - randBegin)); }
  23.  
  24.         for (int head{ 0 }; head < arrSize; ++head)
  25.         {
  26.             noPremutation = true;
  27.             for (int tail{ arrSize - 1 }; tail > head; --tail)
  28.             {
  29.                 if (arr[tail] < arr[tail - 1])
  30.                 {
  31.                     copy = arr[tail - 1];
  32.                     arr[tail - 1] = arr[tail];
  33.                     arr[tail] = copy;
  34.                     ++premutation[Methods::bubleSort];
  35.                     noPremutation = false;
  36.                 }
  37.             }
  38.             if (noPremutation) { break; }
  39.         }
  40.         // min Sort
  41.         for (int i{ 0 }; i < arrSize; ++i) { arr[i] = randBegin + (rand() % (randEnd - randBegin)); }
  42.  
  43.         for (int head{ 0 }; head < arrSize; ++head)
  44.         {
  45.             min = head;
  46.  
  47.             for (int minIdx{ head }; minIdx < arrSize; ++minIdx)
  48.             {
  49.                 if (arr[min] > arr[minIdx]) { min = minIdx; }
  50.             }
  51.  
  52.             if (min != head)
  53.             {
  54.                 copy = arr[head];
  55.                 arr[head] = arr[min];
  56.                 arr[min] = copy;
  57.                 ++premutation[Methods::minSort];
  58.             }
  59.  
  60.         }
  61.     }
  62.     std::cout << "Premutations average BubleSort: " << premutation[Methods::bubleSort] / (double)testsCount << " MinSort: " << premutation[Methods::minSort] / (double)testsCount << '\n';
  63.     return 0;
  64. }
Add Comment
Please, Sign In to add comment