Jump to content

Sorting algorithms/Bogosort: Difference between revisions

+D
(+D)
Line 30:
std::random_shuffle(begin, end);
}</cpp>
=={{header|D}}==
<d>module bogosort ;
import std.stdio, std.random ;
 
bool isSorted(T)(inout T[] a) { // test if a is already sorted
if(a.length <= 1) return true ; // 1-elemented/empty array is defined as sorted
for(int i = 1 ; i < a.length ; i++) if(a[i] < a[i-1]) return false ;
return true ;
}
 
T[] bogosort(T)(T[] s) {
while(!isSorted(s)) {
for(int n = s.length ; n > 1 ; n--) {
int i = rand() % n ; // random shuffling
T tmp = s[i] ; s[i] = s[n - 1] ; s[n - 1] = tmp ;
}
}
return s ;
}
 
void main() {
auto b = [2,7,4,3] ;
writefln("%s", bogosort(b)) ;
writefln("%s", b) ; // sort is in place
}</d>
=={{header|J}}==
bogo=: 3 : 0
Cookies help us deliver our services. By using our services, you agree to our use of cookies.