Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Cocktail sort algorithm Exercise: Sort an array of elements using the Cocktail sort algorithm

C++ Sorting: Exercise-5 with Solution

Write a C++ program to sort an array of elements using the Cocktail sort algorithm.

Sample Solution:

C++ Code :

 //Ref: https://bit.ly/2rcvXK5
#include <algorithm>
#include <iostream>
#include <iterator>
 
template <typename RandomAccessIterator>
void cocktail_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  bool swapped = true;
  while (begin != end-- && swapped) {
    swapped = false;
    for (auto i = begin; i != end; ++i) {
      if (*(i + 1) < *i) {
        std::iter_swap(i, i + 1);
        swapped = true;
      }
    }
    if (!swapped) {
      break;
    }
    swapped = false;
    for (auto i = end - 1; i != begin; --i) {
      if (*i < *(i - 1)) {
        std::iter_swap(i, i - 1);
        swapped = true;
      }
    }
    ++begin;
  }
}
 
int main() {
  int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
  cocktail_sort(std::begin(a), std::end(a));
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}

Sample Output:

Original numbers:
100, 2, 56, 200, -52, 3, 99, 33, 177, -199
Sorted numbers:
-199 -52 2 3 33 56 99 100 177 200 

Flowchart:

Flowchart: Sort an array of elements using the Cocktail sort algorithm

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to sort an array of elements using the Bubble sort algorithm.
Next: Write a C++ program to sort an array of elements using the Counting sort algorithm.

What is the difficulty level of this exercise?