Advertisement
avr39ripe

cppBubleSortPermutationOptimization

May 5th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     const int arrSize{ 10 };
  6.     //int arr[arrSize]{ 6,1,4,2,8,9,11,3,2,1 };
  7.     int tmp;
  8.     int iter{ 0 };
  9.     int permutation{ 0 };
  10.  
  11.     //int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  12.     //int arr[arrSize]{};
  13.     int arr[arrSize]{ 1,1,2,9,3,4,6,9,5,11 };
  14.     for (int i{ 0 }; i < arrSize; ++i) { std::cout << arr[i] << ' '; } std::cout << '\n';
  15.  
  16.     for (int head{ 0 }; head < arrSize; ++head)
  17.     {
  18.         permutation = 0;
  19.         for (int tail{ arrSize - 1 }; tail > head; --tail, ++iter)
  20.         {
  21.             if (arr[tail] < arr[tail - 1])
  22.             {
  23.                 tmp = arr[tail];
  24.                 arr[tail] = arr[tail - 1];
  25.                 arr[tail - 1] = tmp;
  26.                 ++permutation;
  27.  
  28.                 for (int i{ 0 }; i < arrSize; ++i) { std::cout << arr[i] << ' '; } std::cout << '\n';
  29.             }
  30.         }
  31.         if (permutation == 0) { std::cout << "Array already sorted!\n"; break; }
  32.     }
  33.  
  34.     for (int i{ 0 }; i < arrSize; ++i) { std::cout << arr[i] << ' '; } std::cout << '\n';
  35.     std::cout << "Total iteration " << iter << '\n';
  36.     return 0;
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement