About ads on Siafoo
Hide Siafoo is here to make coding less frustrating and to save you time. Learn More Join Siafoo

BogoSort with std::random_shuffle

In Brief: The standard library algorithm random_shuffle makes for an easy implementation of BogoSort in C++.... more
Language C++
# '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.

Keywords bogosort (5)
Implements this Algorithm
Average
5.0
Rated
1
Times
5
4
3
2
1
0
License Public Domain
Lines 22
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users
Sponsored Links
About ads on Siafoo

Comments

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