Sorting algorithms/Bogosort

From Rosetta Code
Revision as of 21:45, 8 May 2008 by rosettacode>Spoon! (remove sections moved to Permutation Sort)
Task
Sorting algorithms/Bogosort
You are encouraged to solve this task according to the task description, using any language you may know.

Bogosort a list of numbers. Bogosort simply shuffles a collection until it is sorted.

Pseudocode:

while not InOrder(list) do Shuffle(list);

C++

The following algorithm actually works for all sequences of comparable types; restricting to lists of integers would not make the code simpler. <cpp>

  1. include <iterator>
  2. include <algorithm>

template<typename ForwardIterator>

void bogosort(ForwardIterator begin, ForwardIterator end)

{

 typedef std::iterator_traits<ForwardIterator>::value_type value_type;
 // if we find two adjacent values where the first is greater than the second, the sequence isn't sorted.
 while (std::adjacent_find(begin, end, std::greater<value_type>()) != end)
   std::random_shuffle(begin, end);

} </cpp>

J

bogo=: 3 : 0
whilst. -. *./ 2 </\ Ry  do. Ry=. (A.~ ?@!@#) y  end. Ry
)

Java

Works with: Java version 1.5+

This implementation works for all comparable types (types with compareTo defined). <java>import java.util.Collections; import java.util.LinkedList;

public class Bogosort<T extends Comparable<T>> { public LinkedList<T> bogoSort(LinkedList<T> list){ boolean sorted= false; while(!sorted){ sorted= true; for(int i= 0;i < list.size() - 1;i++){ if(list.get(i).compareTo(list.get(i + 1)) > 0){ sorted= false; } }

if(!sorted){ Collections.shuffle(list); } } return list; } }</java>