Jump to content

Sorting algorithms/Bogosort: Difference between revisions

(Add Swift)
Line 302:
 
=={{header|C++}}==
Uses C++11. Compile with
The following algorithm actually works for all sequences of comparable types; restricting to lists of integers would not make the code simpler.
g++ -std=c++11 bogo.cpp
<lang cpp>#include <iterator>
<lang cpp>#include <algorithm>
#include <ext/algorithmiostream>
<lang cpp>#include <iterator>
#include <random>
 
/* Sorts anything that provides random access iterators. */
template<typename ForwardIterator>
template<typename RAIterator> void bogo_sort(RAIterator begin,
void bogosort(ForwardIterator begin, ForwardIterator end)
RAIterator end) {
{
std::random_device rd;
typedef std::iterator_traits<ForwardIterator>::value_type value_type;
std::mt19937 generator(rd());
 
while (!__gnu_cxxstd::is_sorted(begin, end)) {
// if we find two adjacent values where the first is greater than the second, the sequence isn't sorted.
while ( std::adjacent_findshuffle(begin, end, std::greater<value_type>()) != endgenerator);
}
std::random_shuffle(begin, end);
}
}</lang>
Using the is_sorted function, part of the SGI STL implementation and C++11:
 
{{works with|GCC}}
<lang cpp>#include <algorithm>
#include <ext/algorithm>
 
int main() {
template<typename ForwardIterator>
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
void bogosort(ForwardIterator begin, ForwardIterator end)
bogo_sort(std::begin(a), std::end(a));
{
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
while (!__gnu_cxx::is_sorted(begin, end))
std::random_shuffle(begin,cout << end)"\n";
}</lang>
Output:
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|C sharp|C#}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.