License Public Domain
Lines 22
Keywords
bogosort (5)
Implements this Algorithm
Permissions
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users

BogoSort with std::random_shuffle Atom Feed 1

In Brief The standard library algorithm random_shuffle makes for an easy implementation of BogoSort in C++.... more
# 's
 1#include <algorithm> // random_shuffle
2#include <vector>
3#include <boost/lexical_cast.hpp> // convert string to int
4
5bool check_sort(std::vector<int>& ar) {
6
7 for(int i = 0; i < ar.size()-1; ++i) {
8 if (ar[i] > ar[i+1]) {
9 return false;
10 }
11 }
12
13 return true;
14}
15
16int main(int argc, char* argv[]) {
17
18 // Create a vector of integers and populate from command line args.
19 std::vector<int> ar;
20 while(*++argv) {
21 ar.push_back(boost::lexical_cast<int>(*argv));
22 }
23
24 while (!check_sort(ar)) {
25 std::random_shuffle(ar.begin(), ar.end());
26 }
27 return 0;
28}

The standard library algorithm random_shuffle makes for an easy implementation of BogoSort in C++.

A sample run:

$ time ./bogosort 1 2 3
real    0m0.003s
$ time ./bogosort 3 2 1
real    0m0.003s
$ time ./bogosort 3 4 5 6 7 1 10 11 41 456 89
real    0m21.229s

To Do

Make check_sort more "std". There might even be a one-liner for this.

Credits

Based on Simple BogoSort implementation.

Comments

over 8 years ago (04 Aug 2008 at 11:55 PM) by Stou S.
I wish it had output, but I give this a 5 for using STL and not reinventing the wheel.