avr39ripe

cppRotateArrEffective

Jul 23rd, 2021
786
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     const int arrSize{ 10 };
  6.     int arr[arrSize]{ 1,2,3,4,5,6,7,8,9,10 };
  7.     const int arrBegin{ 0 };
  8.     const int arrEnd{ arrBegin + arrSize };
  9.     const int rotatePos{ arrSize - 4 };
  10.  
  11.     for (int arrIdx{ arrBegin }; arrIdx != arrEnd; ++arrIdx) { std::cout << arr[arrIdx] << ' '; }std::cout << '\n';
  12.  
  13.     int first{arrBegin};
  14.     int firstNew{ rotatePos };
  15.     int last{arrEnd};
  16.  
  17.     int read{ firstNew };
  18.     int write{ first };
  19.     int readNext{ first }; // read position for when "read" hits "last"
  20.     int copyElement;
  21.  
  22.     while (write != read and read != last)
  23.     {
  24.         while (read != last)
  25.         {
  26.             if (write == readNext)
  27.             {
  28.                 readNext = read; // track where "first" went
  29.             }
  30.  
  31.             copyElement = arr[read];
  32.             arr[read] = arr[write];
  33.             arr[write] = copyElement;
  34.             ++read;
  35.             ++write;
  36.         }
  37.         for (int arrIdx{ arrBegin }; arrIdx != arrEnd; ++arrIdx) { std::cout << arr[arrIdx] << ' '; }std::cout << '\n';
  38.         read = readNext;
  39.     }
  40.  
  41.     //for (int arrIdx{ arrBegin }; arrIdx != arrEnd; ++arrIdx) { std::cout << arr[arrIdx] << ' '; }std::cout << '\n';
  42.  
  43.     return 0;
  44. }
  45.  
  46.  
RAW Paste Data