Sorting algorithms/Bogosort: Difference between revisions

Added Easylang
(Added Easylang)
 
(43 intermediate revisions by 26 users not shown)
Line 1:
{{task|Sorting Algorithms}}
[[Category:Sorting]]
{{Sorting Algorithm}}
 
Line 23 ⟶ 24:
The [[Knuth shuffle]] may be used to implement the shuffle part of this algorithm.
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">F is_sorted(data)
R all((0 .< data.len - 1).map(i -> @data[i] <= @data[i + 1]))
 
F bogosort(&data)
L !is_sorted(data)
random:shuffle(&data)
 
V arr = [2, 1, 3]
bogosort(&arr)
print(arr)</syntaxhighlight>
 
{{out}}
<pre>
[1, 2, 3]
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program bogosort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
qGraine: .quad 123456
TableNumber: .quad 1,2,3,4,5,6,7,8,9,10
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
1:
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl knuthShuffle
// table display elements
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,#1 // sorted ?
bne 1b // no -> loop
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
 
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0
ldr x4,[x0,x2,lsl #3] // load A[0]
1:
add x2,x2,#1
cmp x2,x1 // end ?
bge 99f
ldr x3,[x0,x2, lsl #3] // load A[i]
cmp x3,x4 // compare A[i],A[i-1]
blt 98f // smaller -> error -> return
mov x4,x3 // no -> A[i-1] = A[i]
b 1b // and loop
98:
mov x0,#0 // error
b 100f
99:
mov x0,#1 // ok -> return
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains elements number */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x4,x1 // elements number
mov x3,#0
1: // loop display table
ldr x0,[x2,x3,lsl #3]
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
bl affichageMess // display message
add x3,x3,#1
cmp x3,x4 // end ?
blt 1b // no -> loop
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
/******************************************************************/
/* shuffle game */
/******************************************************************/
/* x0 contains boxs address */
/* x1 contains elements number */
knuthShuffle:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x5,x0 // save table address
mov x2,#0 // start index
1:
mov x0,x2 // generate aleas
bl genereraleas
ldr x3,[x5,x2,lsl #3] // swap number on the table
ldr x4,[x5,x0,lsl #3]
str x4,[x5,x2,lsl #3]
str x3,[x5,x0,lsl #3]
add x2,x2,1 // next number
cmp x2,x1 // end ?
blt 1b // no -> loop
 
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/***************************************************/
/* Generation random number */
/***************************************************/
/* x0 contains limit */
genereraleas:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,qAdrqGraine
ldr x2,[x1]
ldr x3,qNbDep1
mul x2,x3,x2
ldr x3,qNbDep2
add x2,x2,x3
str x2,[x1] // maj de la graine pour l appel suivant
cmp x0,#0
beq 100f
udiv x3,x2,x0
msub x0,x3,x0,x2 // résult = remainder
100: // end function
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrqGraine: .quad qGraine
qNbDep1: .quad 0x0019660d
qNbDep2: .quad 0x3c6ef35f
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC KnuthShuffle(INT ARRAY tab BYTE size)
BYTE i,j
INT tmp
 
i=size-1
WHILE i>0
DO
j=Rand(i+1)
tmp=tab(i)
tab(i)=tab(j)
tab(j)=tmp
i==-1
OD
RETURN
 
BYTE FUNC IsSorted(INT ARRAY tab BYTE size)
BYTE i
 
IF size<2 THEN
RETURN (1)
FI
FOR i=0 TO size-2
DO
IF tab(i)>tab(i+1) THEN
RETURN (0)
FI
OD
RETURN (1)
 
PROC BogoSort(INT ARRAY a INT size)
WHILE IsSorted(a,size)=0
DO
KnuthShuffle(a,size)
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
BogoSort(a,size)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
 
PROC Main()
INT ARRAY
a(10)=[1 4 65535 0 7 4 20 65530],
b(21)=[3 2 1 0 65535 65534 65533],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Test(a,8)
Test(b,7)
Test(c,8)
Test(d,12)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Bogosort.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[1 4 -1 0 7 4 20 -6]
Array after sort:
[-6 -1 0 1 4 4 7 20]
 
Array before sort:
[3 2 1 0 -1 -2 -3]
Array after sort:
[-3 -2 -1 0 1 2 3]
 
Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]
 
Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight lang="actionscript">public function bogoSort(arr:Array):Array
{
while (!sorted(arr))
Line 61 ⟶ 351:
 
return true;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
 
Line 113 ⟶ 403:
Put (Integer'Image (Sequence (I)));
end loop;
end Test_Bogosort;</langsyntaxhighlight>
The solution is generic.
The procedure Bogosort can be instantiated
Line 122 ⟶ 412:
3 6 7 9
</pre>
 
=={{header|ALGOL 68}}==
{{trans|python}}
Line 131 ⟶ 422:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
 
<langsyntaxhighlight lang="algol68">MODE TYPE = INT;
 
PROC random shuffle = (REF[]TYPE l)VOID: (
Line 167 ⟶ 458:
[6]TYPE sample := (61, 52, 63, 94, 46, 18);
print((bogo sort(sample), new line))</langsyntaxhighlight>
{{out}}
+18 +46 +52 +61 +63 +94
Line 173 ⟶ 464:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
 
/* ARM assembly Raspberry PI */
Line 423 ⟶ 714:
bx lr
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">bogoSort: function [items][
a: new items
while [not? sorted? a]-> shuffle 'a
return a
]
 
print bogoSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % Bogosort("987654")
MsgBox % Bogosort("319208")
MsgBox % Bogosort("fedcba")
Line 461 ⟶ 764:
}
Return Found
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Sort standard input and output to the standard output
<langsyntaxhighlight lang="awk">function randint(n)
{
return int(n * rand())
Line 494 ⟶ 797:
print line[i]
}
}</langsyntaxhighlight>
 
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vb">global array
dim array = {10, 1, 2, -6, 3}
lb = array[?,]-1 : ub = array[?]-1
 
print "unsort ";
for i = lb to ub
print rjust(array[i], 4);
next i
 
call Bogosort(array) # ordenar el array
 
print chr(10); " sort ";
for i = lb to ub
print rjust(array[i], 4);
next i
end
 
subroutine shuffle(array)
n = array[?] : m = array[?]*2
 
for k = 1 to m
i = int(Rand*n)
j = int(Rand*n)
tmp = array[i] #swap lb(i), lb(j)
array[i] = array[j]
array[j] = tmp
next k
end subroutine
 
function inorder(array)
n = array[?]
for i = 0 to n-2
if array[i] > array[i+1] then return false
next i
return true
end function
 
subroutine Bogosort(array)
while not inorder(array)
call shuffle(array)
end while
end subroutine</syntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1
Line 520 ⟶ 868:
IF d(I%) < d(I%-1) THEN = FALSE
NEXT
= TRUE</langsyntaxhighlight>
{{out}}
<pre>
383150 shuffles required to sort 10 items.
</pre>
 
=={{header|BQN}}==
Requires the <code>_while_</code> idiom because the recursive version <code>{(𝕊𝕩⊏˜•rand.Deal∘≠)⍟(𝕩≢∧𝕩)𝕩}</code> quickly runs out of stack depth.
 
<syntaxhighlight lang="bqn">_while_←{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}
Bogo←{𝕩⊏˜•rand.Deal≠𝕩}_while_(≢⟜∧)</syntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">bogosort = { list |
sorted = list.sort #Kinda cheating here
while { list != sorted } { list.shuffle! }
Line 533 ⟶ 887:
}
 
p bogosort [15 6 2 9 1 3 41 19]</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
Line 572 ⟶ 926:
for (i=0; i < 6; i++) printf("%d ", numbers[i]);
printf("\n");
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 bogo.cpp
<lang cpp>#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
 
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
 
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
 
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</lang>
{{out}}
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|C#|3.0+}}
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
 
Line 660 ⟶ 977:
 
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 bogo.cpp
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
#include <random>
 
template <typename RandomAccessIterator, typename Predicate>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end,
Predicate p) {
std::random_device rd;
std::mt19937 generator(rd());
while (!std::is_sorted(begin, end, p)) {
std::shuffle(begin, end, generator);
}
}
 
template <typename RandomAccessIterator>
void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) {
bogo_sort(
begin, end,
std::less<
typename std::iterator_traits<RandomAccessIterator>::value_type>());
}
 
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
bogo_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</syntaxhighlight>
{{out}}
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">(defn in-order? [order xs]
(or (empty? xs)
(apply order xs)))
Line 672 ⟶ 1,026:
(recur order (shuffle xs))))
(println (bogosort < [7 5 12 1 4 2 23 18]))</langsyntaxhighlight>
 
=={{header|COBOL}}==
This program generates an array of ten pseudo-random numbers in the range 0 to 999 and then sorts them into ascending order. Eventually.
<langsyntaxhighlight lang="cobol">identification division.
program-id. bogo-sort-program.
data division.
Line 740 ⟶ 1,094:
add 1 to array-index giving adjusted-index.
if item(array-index) is greater than item(adjusted-index)
then move zero to sorted.</langsyntaxhighlight>
{{out}}
<pre>BEFORE SORT: 141 503 930 105 78 518 180 907 791 361
Line 752 ⟶ 1,106:
<code>nshuffle</code> is the same code as in [[Knuth shuffle#Common Lisp|Knuth shuffle]].
 
<langsyntaxhighlight lang="lisp">(defun nshuffle (sequence)
(loop for i from (length sequence) downto 2
do (rotatef (elt sequence (random i))
Line 763 ⟶ 1,117:
(defun bogosort (list predicate)
(do ((list list (nshuffle list)))
((sortedp list predicate) list)))</langsyntaxhighlight>
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">def knuthShuffle(items : Array)
i = items.size-1
while i > 1
j = Random.rand(0..i)
items.swap(i, j)
 
i -= 1
end
end
 
def sorted?(items : Array)
prev = items[0]
items.each do |item|
if item < prev
return false
end
prev = item
end
return true
end
 
def bogoSort(items : Array)
while !sorted?(items)
knuthShuffle(items)
end
end</syntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.random;
 
void bogoSort(T)(T[] data) {
Line 777 ⟶ 1,159:
bogoSort(array);
writeln(array);
}</langsyntaxhighlight>
{{out}}
<pre>[1, 2, 3, 5, 6, 7, 8, 11, 41]</pre>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Sorting_algorithms/Bogosort#Pascal Pascal].
 
=={{header|E}}==
Line 785 ⟶ 1,169:
Using the shuffle from [[Knuth shuffle#E]].
 
<langsyntaxhighlight lang="e">def isSorted(list) {
if (list.size() == 0) { return true }
var a := list[0]
Line 800 ⟶ 1,184:
shuffle(list, random)
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight>
proc shuffle . l[] .
for i = len l[] downto 2
r = randint i
swap l[i] l[r]
.
.
proc issorted . l[] r .
for i = 2 to len l[]
if l[i] < l[i - 1]
r = 0
return
.
.
r = 1
.
proc bogosort . l[] .
repeat
issorted l[] r
until r = 1
shuffle l[]
.
.
list[] = [ 2 7 41 11 3 1 6 5 8 ]
bogosort list[]
print list[]
</syntaxhighlight>
 
{{out}}
<pre>
[ 1 2 3 5 6 7 8 11 41 ]
</pre>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
BOGO_SORT
Line 870 ⟶ 1,288:
 
end
</syntaxhighlight>
</lang >
TEST:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 905 ⟶ 1,323:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 911 ⟶ 1,329:
Sorted: 1 2 3 5 7
</pre>
 
=={{header|Elena}}==
ELENA 45.10 :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
Line 933 ⟶ 1,352:
public program()
{
var list := new int[]::({3, 4, 1, 8, 7, -2, 0)};
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.bogoSorter().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 945 ⟶ 1,364:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def bogo_sort(list) do
if sorted?(list) do
Line 957 ⟶ 1,376:
defp sorted?([x, y | _]) when x>y, do: false
defp sorted?([_, y | rest]), do: sorted?([y | rest])
end</langsyntaxhighlight>
 
Example:
Line 966 ⟶ 1,385:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function shuffle(sequence s)
object temp
integer j
Line 997 ⟶ 1,416:
end function
 
? bogosort(shuffle({1,2,3,4,5,6}))</langsyntaxhighlight>
 
{{out}}
Line 1,010 ⟶ 1,429:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: grouping kernel math random sequences ;
 
: sorted? ( seq -- ? ) 2 <clumps> [ first2 <= ] all? ;
: bogosort ( seq -- newseq ) [ dup sorted? ] [ randomize ] until ;</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,043 ⟶ 1,462:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE BOGO
IMPLICIT NONE
CONTAINS
Line 1,095 ⟶ 1,514:
WRITE (*,*) "Array required", iter, " shuffles to sort"
END PROGRAM BOGOSORT</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
 
<syntaxhighlight lang="freebasic">sub shuffle( a() as long )
dim as ulong n = ubound(a), i, j, k, m = ubound(a)*2
dim as ulong tmp
randomize timer
for k=1 to m
i=int(rnd*n)
j=int(rnd*n)
tmp = a(i)
a(i) = a(j)
a(j) = tmp
next k
end sub
 
function inorder( a() as long ) as boolean
dim as ulong i, n = ubound(a)
for i = 0 to n-2
if a(i)>a(i+1) then
return false
end if
next i
return true
end function
 
sub bogosort( a() as long )
while not inorder(a())
shuffle(a())
wend
end sub
 
dim as long a(5) = {10, 1, 2, -6, 3}
dim as long i
 
bogosort(a())
 
for i=0 to ubound(a) - 1
print a(i)
next i</syntaxhighlight>
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=b2b766f379d809cbf054c2d32d76c453 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim sSorted As String = "123456789" 'The desired outcome
Dim sTest, sChr As String 'Various strings
Line 1,117 ⟶ 1,576:
Print "Solved in " & Str(iCounter) & " loops" 'Print the result
 
End</langsyntaxhighlight>
Output: (This example was completed in under 2 seconds)
<pre>
Line 1,130 ⟶ 1,589:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,151 ⟶ 1,610:
}
fmt.Println("sorted! ", temp)
}</langsyntaxhighlight>
{{out}} (sometimes takes a few seconds)
<pre>
Line 1,160 ⟶ 1,619:
=={{header|Groovy}}==
Solution (also implicitly tracks the number of shuffles required):
<langsyntaxhighlight lang="groovy">def bogosort = { list ->
def n = list.size()
while (n > 1 && (1..<n).any{ list[it-1] > list[it] }) {
Line 1,167 ⟶ 1,626:
}
list
}</langsyntaxhighlight>
 
Test Program:
<langsyntaxhighlight lang="groovy">println (bogosort([3,1,2]))</langsyntaxhighlight>
 
{{out}} trial 1:
Line 1,179 ⟶ 1,638:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random
import Data.Array.IO
import Control.Monad
Line 1,208 ⟶ 1,667:
 
bogosort :: Ord a => [a] -> IO [a]
bogosort = bogosortBy (<)</langsyntaxhighlight>
Example:
<pre>
Line 1,216 ⟶ 1,675:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">procedure shuffle(l)
repeat {
!l :=: ?l
Line 1,232 ⟶ 1,691:
l := [6,3,4,5,1]
|( shuffle(l) & sorted(l)) \1 & every writes(" ",!l)
end</langsyntaxhighlight>
 
=={{header|Inform 6}}==
<langsyntaxhighlight Informlang="inform 6">[ shuffle a n i j tmp;
for(i = n - 1: i > 0: i--)
{
Line 1,260 ⟶ 1,719:
shuffle(a, n);
}
];</langsyntaxhighlight>
 
=={{header|Insitux}}==
 
{{Trans|Clojure}}
 
<syntaxhighlight lang="insitux">(function bogo-sort order list
(return-unless (1 list) [])
(if (... order list)
list
(recur order (shuffle list))))
(bogo-sort < [7 5 12 1 4 2 23 18])</syntaxhighlight>
 
Even with this small list the web REPL sometimes exceeds its default recur budget (1e4 - 10000):
 
<pre>4:6 (recur order (shuffle list))))
Budget Error: recurred too many times.</pre>
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">List do(
isSorted := method(
slice(1) foreach(i, x,
Line 1,279 ⟶ 1,755:
 
lst := list(2, 1, 4, 3)
lst bogoSortInPlace println # ==> list(1, 2, 3, 4), hopefully :)</langsyntaxhighlight>
 
=={{header|J}}==
{{eff note|J|/:~}}
<langsyntaxhighlight lang="j">bogo=: monad define
whilst. +./ 2 >/\ Ry do. Ry=. (A.~ ?@!@#) y end. Ry
)</langsyntaxhighlight>
 
=={{header|Java}}==
Without Collections, Lists or Iterators. With a counter.
<langsyntaxhighlight lang="java">
 
public class BogoSort
Line 1,344 ⟶ 1,821:
 
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,354 ⟶ 1,831:
{{works with|Java|1.5+}}
This implementation works for all comparable types (types with <tt>compareTo</tt> defined).
<langsyntaxhighlight lang="java5">import java.util.Collections;
import java.util.List;
import java.util.Iterator;
Line 1,377 ⟶ 1,854:
Collections.shuffle(list);
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">shuffle = function(v) {
for(var j, x, i = v.length; i; j = Math.floor(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
return v;
Line 1,399 ⟶ 1,876:
}
return v;
}</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function bogosort!(arr::AbstractVector)
while !issorted(arr)
shuffle!(arr)
Line 1,412 ⟶ 1,889:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", bogosort!(v))</langsyntaxhighlight>
 
{{out}}
Line 1,420 ⟶ 1,897:
=={{header|Kotlin}}==
{{trans|C}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
const val RAND_MAX = 32768 // big enough for this
Line 1,455 ⟶ 1,932:
bogosort(a)
println("After sorting : ${a.contentToString()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,464 ⟶ 1,941:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function bogosort (list)
if type (list) ~= 'table' then return list end
 
Line 1,489 ⟶ 1,966:
 
return list
end</langsyntaxhighlight>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
define(`randSeed',141592653)
define(`setRand',
Line 1,531 ⟶ 2,008:
show(`b')
bogosort(`b')
show(`b')</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">arr := Array([2,3,1]):
len := numelems(arr):
#Translation of C, random swapping
Line 1,549 ⟶ 2,026:
shuffle_arr(arr, len):
end do:
arr;</langsyntaxhighlight>
{{Out|Output}}
<pre>[1 2 3]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Bogosort[x_List] := Block[{t=x},While[!OrderedQ[t],t=RandomSample[x]]; t]
 
Bogosort[{1, 2, 6, 4, 0, -1, Pi, 3, 5}]
=> {-1, 0, 1, 2, 3, Pi, 4, 5, 6}</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab">function list = bogoSort(list)
while( ~issorted(list) ) %Check to see if it is sorted
list = list( randperm(numel(list)) ); %Randomly sort the list
end
end</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight MATLABlang="matlab">bogoSort([5 3 8 4 9 7 6 2 1])
 
ans =
 
1 2 3 4 5 6 7 8 9
</syntaxhighlight>
</lang>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn notSorted arr =
(
if arr.count > 0 then
Line 1,611 ⟶ 2,087:
)
arr
)</langsyntaxhighlight>
 
=={{header|Modula-3}}==
 
<langsyntaxhighlight lang="modula3">MODULE Bogo EXPORTS Main;
 
IMPORT IO, Fmt, Random;
Line 1,660 ⟶ 2,136:
END;
IO.Put("\nRequired " & Fmt.Int(count) & " shuffles\n");
END Bogo.</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">def sorted(list)
if len(list) = 0
return true
end
 
for i in range(0, len(list) - 2)
if list[i] > list[i + 1]
return false
end
end
 
return true
end
 
def bogosort(list)
while not sorted(list)
list = list.shuffle()
end
 
return list
end</syntaxhighlight>
 
=={{header|Nemerle}}==
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
using Nemerle.Imperative;
Line 1,701 ⟶ 2,200:
foreach (i in sortme) Write($"$i ");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
{{trans|Java}}
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 1,751 ⟶ 2,250:
method isFalse public static returns boolean
return \isTrue
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,759 ⟶ 2,258:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import mathrandom
randomize()
 
randomize()
proc shuffle[T](x: var openarray[T]) =
for i in countdown(x.high, 0):
let j = random(i + 1)
swap(x[i], x[j])
 
proc isSorted[T](s: openarray[T]): bool =
Line 1,780 ⟶ 2,275:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
bogoSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
Line 1,786 ⟶ 2,281:
=={{header|Oberon-2}}==
{{Works with|Oxford Oberon-2 Compiler}}
<langsyntaxhighlight lang="oberon2">MODULE Bogo;
 
IMPORT Out, Random;
Line 1,836 ⟶ 2,331:
END;
Out.Ln;
END Bogo.</langsyntaxhighlight>
 
Init initializes the array as 1 thru 10, then it is shuffled, and then the while loop continually shuffles until Sorted returns true.
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec is_sorted comp = function
| e1 :: e2 :: r -> comp e1 e2 <= 0 && is_sorted comp (e2 :: r)
| _ -> true
Line 1,860 ⟶ 2,355:
li
else
bogosort (shuffle li)</langsyntaxhighlight>
Example:
<pre>
Line 1,870 ⟶ 2,365:
We use an array because that made most sense for the Knuth Shuffle task. Usually you would use lists for stuff like this in Oz.
 
<langsyntaxhighlight lang="oz">declare
proc {BogoSort Arr}
for while:{Not {InOrder Arr}} do
Line 1,901 ⟶ 2,396:
in
{BogoSort X}
{Show {Array.toRecord unit X}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
This implementation sorts 9 distinct elements in only 600 milliseconds.
<langsyntaxhighlight lang="parigp">bogosort(v)={
while(1,
my(u=vecextract(v,numtoperm(#v,random((#v)!))));
Line 1,911 ⟶ 2,406:
return(u)
);
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
 
<langsyntaxhighlight Pascallang="pascal">program bogosort;
 
const
Line 1,979 ⟶ 2,474:
a[i] := (max + 1) - i;
bogo(a);
end.</langsyntaxhighlight>
 
{{out}}
Line 1,989 ⟶ 2,484:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util qw(shuffle);
 
sub bogosort
Line 2,001 ⟶ 2,496:
{$_ >= $last or return 0;
$last = $_;}
return 1;}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>sub bogosort (@list is copy) {
@list .= pick(*) until [<=] @list;
return @list;
}
 
my @nums = (^5).map: { rand };
say @nums.sort.Str eq @nums.&bogosort.Str ?? 'ok' !! 'not ok';
</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function inOrder(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
return s==sort(s) -- <snigger>
end function
 
function bogosort(sequence s)
while not inOrder(s) do
? s
s = shuffle(s)
end while
return s
end function
<span style="color: #008080;">function</span> <span style="color: #000000;">inOrder</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
? bogosort(shuffle({1,2,3,4,5,6}))</lang>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">==</span><span style="color: #7060A8;">sort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span> <span style="color: #000080;font-style:italic;">-- &lt;snigger&gt;</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">bogosort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #000000;">inOrder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">s</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span> <span style="color: #000000;">bogosort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">({</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">}))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 2,037 ⟶ 2,526:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function bogosort($l) {
while (!in_order($l))
shuffle($l);
Line 2,048 ⟶ 2,537:
return FALSE;
return TRUE;
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de bogosort (Lst)
(loop
(map
'((L) (rot L (rand 1 (length L))))
Lst )
(T (apply <= Lst) Lst) ) )</langsyntaxhighlight>
{{out}}
<pre>: (bogosort (make (do 9 (link (rand 1 999)))))
Line 2,069 ⟶ 2,558:
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang="pli">*process source xref;
bogosort: Proc Options(main);
Dcl SYSPRINT Print;
Line 2,122 ⟶ 2,611:
Return(res);
End;
End;</langsyntaxhighlight>
{{out}}
<pre>un-bogoed
Line 2,140 ⟶ 2,629:
=={{header|PowerShell}}==
Shuffle taken from [[Knuth Shuffle]]
<langsyntaxhighlight PowerShelllang="powershell">function shuffle ($a) {
$c = $a.Clone() # make copy to avoid clobbering $a
1..($c.Length - 1) | ForEach-Object {
Line 2,168 ⟶ 2,657:
}
 
$l = 7; BogoSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|Prolog}}==
<syntaxhighlight lang="prolog">bogo_sort(L,Rl) :-
min_list(L,Min),
repeat,
random_permutation(L,Rl),
is_sorted(Rl,Min),
!.
is_sorted([],_).
is_sorted([N|T],P) :-
N >= P,
is_sorted(T,N).</syntaxhighlight>
{{out}}
<pre>
?- bogo_sort( [703,931,12,713,894,232,778,86,700,26] ,Sorted).
Sorted = [12,26,86,232,700,703,713,778,894,931] .
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure KnuthShuffle (Array a(1))
Protected i, Size = ArraySize(a())
For i = 0 To Size
Line 2,203 ⟶ 2,710:
Next
 
BogoSort(b())</langsyntaxhighlight>
{{out}}
<pre>Array of 10 integers required 2766901 shuffles To SORT.</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import random
 
def bogosort(l):
Line 2,223 ⟶ 2,730:
return False
last = x
return True</langsyntaxhighlight>
 
Alternative definition for ''in_order'' (Python 2.5)
<langsyntaxhighlight lang="python">def in_order(l):
return all( l[i] <= l[i+1] for i in xrange(0,len(l)-1))</langsyntaxhighlight>
 
An alternative implementation for Python 2.5 or later:
<langsyntaxhighlight lang="python">import random
def bogosort(lst):
random.shuffle(lst) # must shuffle it first or it's a bug if lst was pre-sorted! :)
while lst != sorted(lst):
random.shuffle(lst)
return lst</langsyntaxhighlight>
 
Another alternative implementation, using iterators for maximum efficiency:
 
<langsyntaxhighlight lang="python">import operator
import random
from itertools import dropwhile, imap, islice, izip, repeat, starmap
Line 2,250 ⟶ 2,757:
bogosort = lambda l: next(dropwhile(
lambda l: not all(starmap(operator.le, izip(l, islice(l, 1, None)))),
imap(shuffled, repeat(l))))</langsyntaxhighlight>
 
=={{header|Qi}}==
<syntaxhighlight lang="qi">
<lang Qi>
(define remove-element
0 [_ | R] -> R
Line 2,277 ⟶ 2,784:
Suggestion -> Suggestion where (in-order? Suggestion)
Suggestion -> (bogosort (shuffle Suggestion)))
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
<syntaxhighlight lang="quackery">[ true swap
dup [] != if
[ behead swap witheach
[ tuck > if
[ dip not
conclude ] ] ]
drop ] is inorder ( [ --> b )
 
[ dup inorder not while shuffle again ] is bogosort ( [ --> [ )</syntaxhighlight>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">bogosort <- function(x) {
while(is.unsorted(x)) x <- sample(x)
x
Line 2,286 ⟶ 2,804:
 
n <- c(1, 10, 9, 7, 3, 0)
bogosort(n)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,293 ⟶ 2,811:
is unit tests and an example.
 
<langsyntaxhighlight lang="racket">
#lang racket
(define (bogo-sort l) (if (apply <= l) l (bogo-sort (shuffle l))))
Line 2,304 ⟶ 2,822:
(displayln unsorted)
(displayln (bogo-sort unsorted)))
</syntaxhighlight>
</lang>
 
{{out}} (chances are you won't get quite this!):
Line 2,311 ⟶ 2,829:
(12 26 86 232 700 703 713 778 894 931)
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub bogosort (@list is copy) {
@list .= pick(*) until [<=] @list;
return @list;
}
 
my @nums = (^5).map: { rand };
say @nums.sort.Str eq @nums.&bogosort.Str ?? 'ok' !! 'not ok';
</syntaxhighlight>
 
=={{header|REXX}}==
===true bogo sort===
<langsyntaxhighlight lang="rexx">/*REXX program performs a type of bogo sort on numbers in an array. */
parse arg list /*obtain optional list from C.L. */
if list='' then list=-21 333 0 444.4 /*Not defined? Then use default.*/
Line 2,344 ⟶ 2,873:
end /*t*/
say
return</langsyntaxhighlight>
{{out}} using the default input:
<pre>
Line 2,367 ⟶ 2,896:
<br>has already been sorted and including the number out-of-order. &nbsp; The search then starts over.
<br>This is repeated as often as it takes to finally get the array in order.
<langsyntaxhighlight lang="rexx">/*REXX program performs a type of bogo sort on numbers in an array. */
@.1 = 0 ; @.11= -64 ; @.21= 4096 ; @.31= 6291456
@.2 = 0 ; @.12= 64 ; @.22= 40960 ; @.32= 5242880
Line 2,408 ⟶ 2,937:
end /*t*/
say
return</langsyntaxhighlight>
{{out}}
<pre style="height:30ex">
Line 2,519 ⟶ 3,048:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting algorithms/Bogosort
 
Line 2,560 ⟶ 3,089:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 2,566 ⟶ 3,095:
[0, 1, 2, 2, 4, 31, 65, 83, 99, 782]
</pre>
 
=={{header|RPL}}==
<code>KNUTH</code> is defined at [[Knuth shuffle#RPL|Knuth shuffle]]
{{works with|HP|48G}}
≪ '''WHILE''' DUP ΔLIST ≪ MIN ≫ STREAM 0 < '''REPEAT'''
<span style="color:blue">KNUTH</span>
'''END'''
≫ '<span style="color:blue">BOGOSORT</span>' STO
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def shuffle(l)
l.sort_by { rand }
end
Line 2,579 ⟶ 3,116:
def in_order(l)
(0..l.length-2).all? {|i| l[i] <= l[i+1] }
end</langsyntaxhighlight>
 
An alternative implementation:
 
<langsyntaxhighlight lang="ruby">def shuffle(l)
l.sort_by { rand }
end
Line 2,590 ⟶ 3,127:
l = shuffle(l) until l == l.sort
l
end</langsyntaxhighlight>
 
{{works with|Ruby|1.8.7+}}
 
<langsyntaxhighlight lang="ruby">def in_order(l)
(0..l.length-2).all? {|i| l[i] <= l[i+1] }
end
Line 2,601 ⟶ 3,138:
l.shuffle! until in_order(l)
l
end</langsyntaxhighlight>
 
=={{header|Rust}}==
Works with Rust 1.11+, requires rand module
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
use rand::Rng;
 
Line 2,633 ⟶ 3,170:
println!("{:?}", testlist);
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
{{works with|Scala|2.8}}
<langsyntaxhighlight lang="scala">def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head <= s.last)
def bogosort(l: List[Int]): List[Int] = if (isSorted(l)) l else bogosort(scala.util.Random.shuffle(l))</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func in_order(a) {
return true if (a.len <= 1);
var first = a[0];
a.ftlast(-1).all { |elem| first <= elem  ? do { first = elem; true }  : false }
}
 
func bogosort(a) {
a.shuffle! while  !in_order(a);
return a;
}
 
var arr = 5.of { 100.rand.intirand };
say "Before: #{arr}";
say "After: #{bogosort(arr)}";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,660 ⟶ 3,197:
After: 33 45 57 83 85
</pre>
 
=={{header|Scheme}}==
Uses [[Knuth shuffle]] to shuffle the list.
<syntaxhighlight lang="scheme">(import (rnrs base (6))
(srfi :27 random-bits))
 
(define (shuffle lst)
(define (swap! vec i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)))
(define vec (list->vector lst))
(let loop ((i (sub1 (vector-length vec))))
(unless (zero? i)
(swap! vec i (random-integer (add1 i)))
(loop (sub1 i))))
(vector->list vec))
 
(define (sorted? lst pred?)
(cond
((null? (cdr lst)) #t)
((pred? (car lst) (cadr lst)) (sorted? (cdr lst) pred?))
(else #f)))
 
(define (bogosort lst)
(if (sorted? lst <)
lst
(bogosort (shuffle lst))))
 
 
(let ((input '(5 4 3 2 1)))
(display "Input: ")
(display input)
(newline)
(display "Output: ")
(display (bogosort input))
(newline))</syntaxhighlight>
{{out}}
<pre>Input: (5 4 3 2 1)
Output: (1 2 3 4 5)</pre>
 
=={{header|Smalltalk}}==
Line 2,665 ⟶ 3,242:
 
This implementation uses closures rather than extending collections to provide a bogosort method.
<langsyntaxhighlight lang="smalltalk">Smalltalk at: #isItSorted put: [ :c |
|isit|
isit := false.
Line 2,688 ⟶ 3,265:
tobesorted := { 2 . 7 . 5 . 3 . 4 . 8 . 6 . 1 }.
bogosort value: tobesorted.
tobesorted displayNl.</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
 
<langsyntaxhighlight SNOBOL4lang="snobol4">* Library for random()
-include 'Random.sno'
 
Line 2,732 ⟶ 3,309:
* # Test and display
bogo(s2a('5 4 3 2 1',5))
end</langsyntaxhighlight>
 
{{out}}
Line 2,742 ⟶ 3,319:
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">import Darwin
 
func shuffle<T>(inout array: [T]) {
Line 2,764 ⟶ 3,341:
shuffle(&ary)
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc shuffleInPlace {listName} {
Line 2,796 ⟶ 3,373:
}
return $list
}</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 2,847 ⟶ 3,424:
=={{header|Ursala}}==
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 2,856 ⟶ 3,433:
#cast %nL
 
example = bogosort <8,50,0,12,47,51></langsyntaxhighlight>
{{out}}
<pre><0,8,12,47,50,51></pre>
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Function Knuth(a As Variant) As Variant
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
Line 2,896 ⟶ 3,473:
Public Sub main()
Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ")
End Sub</langsyntaxhighlight>
<pre>...
1, 3, 2, 5, 6, 4
Line 2,903 ⟶ 3,480:
2, 6, 3, 4, 1, 5
1, 2, 3, 4, 5, 6</pre>
 
=={{header|VBScript}}==
=====Implementation=====
<langsyntaxhighlight lang="vb">sub swap( byref a, byref b )
dim tmp
tmp = a
Line 2,934 ⟶ 3,512:
next
inOrder = res
end function</langsyntaxhighlight>
 
=====Invocation=====
<langsyntaxhighlight lang="vb">dim a
a = array(11, 1, 2, 3, 4, 4, 6, 7, 8)
 
Line 2,946 ⟶ 3,524:
wend
wscript.echo timer-t, "seconds"
wscript.echo join( a, ", " )</langsyntaxhighlight>
 
=====A few outputs (timed)=====
Line 2,958 ⟶ 3,536:
1.980469 seconds
1, 2, 3, 4, 4, 6, 7, 8, 11
</pre>
 
=={{header|V (Vlang)}}==
Updated for V (Vlang) version 0.2.2
<syntaxhighlight lang="go">import rand
 
fn shuffle_array(mut arr []int) {
for i := arr.len - 1; i >= 0; i-- {
j := rand.intn(i + 1)
arr[i], arr[j] = arr[j], arr[i]
}
}
 
fn is_sorted(arr []int) bool {
for i := 0; i < arr.len - 1; i++ {
if arr[i] > arr[i + 1] {
return false
}
}
return true
}
 
fn sort_array(mut arr []int) {
for !is_sorted(arr) {
shuffle_array(mut arr)
println('After Shuffle: $arr')
}
}
 
fn main() {
mut array := [6, 9, 1, 4]
println('Input: $array')
sort_array(mut array)
println('Output: $array')
}</syntaxhighlight>
{{out}}
<pre>Input: [6, 9, 1, 4]
After Shuffle: [1, 9, 6, 4]
After Shuffle: [4, 1, 6, 9]
After Shuffle: [1, 9, 4, 6]
After Shuffle: [9, 1, 4, 6]
After Shuffle: [9, 6, 1, 4]
After Shuffle: [1, 4, 6, 9]
Output: [1, 4, 6, 9]</pre>
 
=={{header|Wren}}==
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "random" for Random
import "./sort" for Sort
 
var bogoSort = Fn.new { |a|
var rand = Random.new()
while (!Sort.isSorted(a)) rand.shuffle(a)
}
 
var a = [31, 41, 59, 26, 53, 58, 97, 93, 23, 84]
System.print("Before: %(a)")
bogoSort.call(a)
System.print("After : %(a)")</syntaxhighlight>
 
{{out}}
<pre>
Before: [31, 41, 59, 26, 53, 58, 97, 93, 23, 84]
After : [23, 26, 31, 41, 53, 58, 59, 84, 93, 97]
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Ran=1, ChOut=8, IntOut=11;
 
proc BogoSort(A, L); \Sort array A of length L
Line 2,980 ⟶ 3,622:
BogoSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 2,986 ⟶ 3,628:
-5 1 1 2 3 4 4 5 6 9
</pre>
 
 
=={{header|Yabasic}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="yabasic">dim a(5)
a (0) = 10: a (1) = 1: a (2) = 2: a (3) = -6: a (4) = 3
 
Bogosort(a())
 
for i = 0 to arraysize(a(),1) - 1
print a(i), " ";
next i
end
 
sub shuffle(a())
n = arraysize(a(),1)
m = arraysize(a(),1)*2
for k = 1 to m
i = int(Ran(n))
j = int(Ran(n))
tmp = a(i) //swap a(i), a(j)
a(i) = a(j)
a(j) = tmp
next k
end sub
 
sub inorder(a())
n = arraysize(a(),1)
for i = 0 to n-2
if a(i) > a(i+1) return false
next i
return true
end sub
 
sub Bogosort(a())
while not inorder(a())
shuffle(a())
wend
end sub</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn increasing(list){
list.len()<2 or
list.reduce(fcn(a,b){ if(b<a) return(Void.Stop,False); b }).toBool()
Line 2,995 ⟶ 3,678:
ns:=L(5,23,1,6,123,7,23);
while(not increasing(ns)){ ns=ns.shuffle() }
ns.println();</langsyntaxhighlight>
{{out}}
<pre>L(1,5,6,7,23,23,123)</pre>
1,969

edits