avr39ripe

cppTelMobSortMenu

Apr 3rd, 2021 (edited)
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int main()
  4. {
  5.     const int arrSize{ 5 };
  6.     int tels[arrSize]{ 1234,9753,2468,5678,3232 };
  7.     int mobs[arrSize]{ 2222,1111,4444,6666,5555 };
  8.     bool correct{ false };
  9.     char menu{ 'a' };
  10.     int tmp;
  11.  
  12.     do
  13.     {
  14.         do
  15.         {
  16.             std::cout << "\na - List all users\nb - Sort by tel\nc - Sort by mob\nx - Exit\n";
  17.             std::cin >> menu;
  18.             correct = menu == 'a' or menu == 'b' or menu == 'c' or menu == 'x';
  19.             if (!correct)
  20.             {
  21.                 std::cout << "\nInvalid menu entry! Try again!\n";
  22.             }
  23.         } while (!correct);
  24.  
  25.         // do we need to sort something??
  26.         if (menu == 'b' or menu == 'c')
  27.         {
  28.             for (int head{ 0 }; head < arrSize; ++head)
  29.             {
  30.                 for (int tail{ arrSize - 1 }; tail > head; --tail)
  31.                 {
  32.                     // if we get there so either 'b' or 'c' menu was chosen
  33.                     // so we choice sorting criteria
  34.                     // 'b' - sort by tel, so element swap in BOTH array when tels[tail]<tels[head]
  35.                     // not 'b' in this case - just 'c' - sort by mobs, so element swap in BOTH array when mobs[tail]<mobs[head]
  36.                     if ((menu == 'b' ? tels[tail] < tels[head] : mobs[tail] < mobs[head]))
  37.                     {
  38.                         tmp = tels[head];
  39.                         tels[head] = tels[tail];
  40.                         tels[tail] = tmp;
  41.  
  42.                         tmp = mobs[head];
  43.                         mobs[head] = mobs[tail];
  44.                         mobs[tail] = tmp;
  45.  
  46.                     }
  47.                 }
  48.             }
  49.         }
  50.         // display users after sorting or by 'a' menu request, if menu == 'x' do nothing
  51.         if (menu != 'x')
  52.         {
  53.             std::cout << "Tel#\tMob#\n";
  54.             for (int i{ 0 }; i < arrSize; ++i)
  55.             {
  56.                 std::cout << tels[i] << '\t' << mobs[i] << '\n';
  57.             }
  58.         }
  59.  
  60.     } while (menu != 'x');
  61.  
  62.     return 0;
  63. }
Add Comment
Please, Sign In to add comment