Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<list>
- #include<algorithm>
- // Just to save time on writing prints
- template<typename T>
- void print(T something)
- {
- std::cout << something << " ";
- }
- // Basically Bubble Sort with backward passes
- void sortCocktailStyle(std::list<int>& arr)
- {
- bool notSorted = true;
- std::list<int>::iterator start = arr.begin();
- std::list<int>::iterator end = arr.end();
- std::list<int>::reverse_iterator rstart = arr.rbegin();
- std::list<int>::reverse_iterator rend = arr.rend();
- end--;
- rend--;
- while (notSorted)
- {
- notSorted = false;
- std::list<int>::iterator current = start;
- while (current != end)
- {
- std::list<int>::iterator next = current;
- ++next;
- if (*next < *current)
- {
- iter_swap(next, current);
- notSorted = true;
- }
- ++current;
- }
- --end;
- // So that we know each forward pass
- for (std::list<int>::iterator it = arr.begin(); it != arr.end()--; it++)
- {
- print(*it);
- }
- print("\n");
- std::list<int>::reverse_iterator rcurrent = rstart;
- while (rcurrent != rend)
- {
- std::list<int>::reverse_iterator next = rcurrent;
- ++next;
- if (*next > *rcurrent)
- {
- iter_swap(next, rcurrent);
- notSorted = true;
- }
- ++rcurrent;
- }
- --rend;
- // So that we know each backward pass
- for (std::list<int>::iterator it = arr.begin(); it != arr.end()--; it++)
- {
- print(*it);
- }
- print("\n");
- }
- }
- int main()
- {
- std::list<int> arr = {5, 1, 4, 2, 8, 0, 2};
- sortCocktailStyle(arr);
- system("pause");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement