Advertisement
AmbushedRaccoon

Bubble sort iterators

Jul 18th, 2025
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. template <typename Iterator, typename Predicate = std::greater<>>
  2. void bubbleSort(Iterator begin, Iterator end, Predicate pred = Predicate())
  3. {
  4.     if (begin == end) return;
  5.  
  6.     for (auto i = begin; i != end; ++i)
  7.     {
  8.         for (auto j = begin; std::next(j) != end; ++j)
  9.         {
  10.             if (pred(*j, *std::next(j)))
  11.             {
  12.                 std::iter_swap(j, std::next(j));
  13.             }
  14.         }
  15.     }
  16. }
  17.  
  18. void sortTest()
  19. {
  20.     std::vector<int> data = {5, 3, 8, 1, 2};
  21.  
  22.     // Sort in ascending order (default)
  23.     bubbleSort(data.begin(), data.end());
  24.  
  25.     for (const auto &val : data)
  26.     {
  27.         std::cout << val << " ";
  28.     }
  29.     std::cout << std::endl;
  30.  
  31.     // Sort in descending order
  32.     bubbleSort(data.begin(), data.end(), std::less<>());
  33.  
  34.     for (const auto &val : data)
  35.     {
  36.         std::cout << val << " ";
  37.     }
  38.     std::cout << std::endl;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement