Advertisement
spiderjako

Shaker Sort

Dec 15th, 2019
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.54 KB | None | 0 0
  1. #include<iostream>
  2. #include<list>
  3. #include<algorithm>
  4.  
  5. // Just to save time on writing prints
  6. template<typename T>
  7. void print(T something)
  8. {
  9.     std::cout << something << " ";
  10. }
  11.  
  12. // Basically Bubble Sort with backward passes
  13. void sortCocktailStyle(std::list<int>& arr)
  14. {
  15.     bool notSorted = true;
  16.     std::list<int>::iterator start = arr.begin();
  17.     std::list<int>::iterator end = arr.end();
  18.     std::list<int>::reverse_iterator rstart = arr.rbegin();
  19.     std::list<int>::reverse_iterator rend = arr.rend();
  20.     end--;
  21.     rend--;
  22.  
  23.     while (notSorted)
  24.     {
  25.         notSorted = false;
  26.  
  27.         std::list<int>::iterator current = start;
  28.         while (current != end)
  29.         {
  30.             std::list<int>::iterator next = current;
  31.             ++next;
  32.             if (*next < *current)
  33.             {
  34.                 iter_swap(next, current);
  35.                 notSorted = true;
  36.             }
  37.  
  38.             ++current;
  39.         }
  40.         --end;
  41.        
  42.         // So that we know each forward pass
  43.         for (std::list<int>::iterator it = arr.begin(); it != arr.end()--; it++)
  44.         {
  45.             print(*it);
  46.         }
  47.         print("\n");
  48.  
  49.         std::list<int>::reverse_iterator rcurrent = rstart;
  50.         while (rcurrent != rend)
  51.         {
  52.             std::list<int>::reverse_iterator next = rcurrent;
  53.             ++next;
  54.             if (*next > *rcurrent)
  55.             {
  56.                 iter_swap(next, rcurrent);
  57.                 notSorted = true;
  58.             }
  59.  
  60.             ++rcurrent;
  61.         }
  62.         --rend;
  63.  
  64.         // So that we know each backward pass
  65.         for (std::list<int>::iterator it = arr.begin(); it != arr.end()--; it++)
  66.         {
  67.             print(*it);
  68.         }
  69.         print("\n");
  70.     }
  71. }
  72.  
  73. int main()
  74. {
  75.     std::list<int> arr = {5, 1, 4, 2, 8, 0, 2};
  76.     sortCocktailStyle(arr);
  77.     system("pause");
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement