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++ Bogosort algorithm Exercise: Sort a list of numbers using Bogosort algorithm

C++ Sorting: Exercise-3 with Solution

Write a C++ program to sort a list of numbers using Bogosort algorithm.

Sample Solution:

C++ Code :

 //Ref: https://bit.ly/2rcvXK5
#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
 
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
               Predicate p) {
  std::random_device rd;
  std::mt19937 generator(rd());
  while (!std::is_sorted(begin, end, p)) {
    std::shuffle(begin, end, generator);
  }
}
 
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
  bogo_sort(
      begin, end,
      std::less<
          typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
 
int main() {
  int a[] = {125, 0, 695, 3, -256, -5, 214, 44, 55};
  std::cout << "Original numbers:\n";
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
  bogo_sort(std::begin(a), std::end(a));
  std::cout << "Sorted numbers:\n";
  copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
  std::cout << "\n";
}

Sample Output:

Original numbers:
125 0 695 3 -256 -5 214 44 55 
Sorted numbers:
-256 -5 0 3 44 55 125 214 695 

Flowchart:

Flowchart: Sort a list of numbers using Bogosort algorithm

C++ Code Editor:

Contribute your code and comments through Disqus.

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

What is the difficulty level of this exercise?