Kody źródłowe/Bogosort
C++
edytujW stylu biblioteki STL
template <class RandomAccesIterator>
bool is_sorted(RandomAccessIterator first, RandomAccessIterator last) {
RandomAccessIterator prev = first++;
for(; first != last; ++first) {
if(*first > *prev) return false;
++prev;
}
return true;
}
template <class RandomAccesIterator>
void bogosort(RandomAccessIterator first, RandomAccessIterator last) {
while(!is_sorted(first, last)) random_shuffle(first, last);
}
Java
edytujpublic void bogoSort(int[] n) {
Random random = new Random();
mainloop: do {
for (int i = 0; i < n.length; i++) {
if(i == n.length-1) {
break mainloop;
}
if (n[i] > n[i+1]) {
break;
}
}
for (int i = n.length - 1; i > 0; i--) {
int swapPosition = random.nextInt(i + 1);
int temp = n[i];
n[i] = n[swapPosition];
n[swapPosition] = temp;
}
} while (true);
}
Python
edytujfrom random import shuffle
from itertools import izip, tee
def in_order(my_list):
"""Check if my_list is ordered"""
it1, it2 = tee(my_list)
it2.next()
return all(a<=b for a,b in izip(it1, it2))
def bogo_sort(my_list):
"""Bogo-sorts my_list in place."""
while not in_order(my_list):
shuffle(my_list)