[Question]
  [
Is [solving Sudoku](https://codegolf.stackexchange.com/questions/355/implement-a-non-guessing-sudoku-solver) too hard? Even the [brute force](https://codegolf.stackexchange.com/questions/378/implement-a-brute-force-sudoku-solver) version? Here's a coding exercise that's a little easier. I hope. :-P
Write the shortest function to implement bogosort. In specific, your function should:
* Take an array (or your language's equivalent) as input
* Check if its elements are in sorted order; if so, return the array
* If not, shuffle the elements, and start again
The shortest entry wins. In the case of a tie, a function that supports a custom comparator (and/or pseudorandom number generator) is favoured. Any remaining ties are resolved by favouring the earlier submission.
---
**Clarifications:** You can use any element type you want, as long as there's some way to order them, of course. Also, the shuffling has to be uniform; none of this "I'll just quicksort it and call it shuffled" business. :-)
  
[Answer]
## Perl 6: 23 chars
```
@s.=pick(*)until[<=] @s
```
[Answer]
## APL(Dyalog), 20
```
{⍵≡⍵[⍋⍵]:⍵⋄∇⍵[?⍨⍴⍵]}
```
**Explanation**
`⍵` is the (right) argument  
`⍵≡⍵[⍋⍵]`: Checks if `⍵` sorted equals `⍵` itself  
`:⍵`: If yes, then return `⍵`  
`∇⍵[?⍨⍴⍵]`: Else, generate an array of 1 to `⍴⍵` (length of `⍵`) in random order, reorder `⍵` according to that (`⍵[...]`), and apply the function to it (`∇`)
---
Suddenly revisiting this problem and...
## APL(Dyalog), 19
```
{∧/2≤/⍵:⍵⋄∇⍵[?⍨⍴⍵]}
```
Was just thinking about sorting an array in the check makes it kind of pointless (not saying that Bogosort is meaningful), a more accurate implementation would be `∧/2≤/⍵`, and that happens to lower the char count.
[Answer]
### APL (22)
```
{(⍳X←⍴⍵)≡⍋⍵:⍵⋄∇⍵[X?X]}
```
Usage:
```
    {(⍳X←⍴⍵)≡⍋⍵:⍵⋄∇⍵[X?X]} 3 2 1
1 2 3
```
Explanation:
* `⍋⍵`: returns the *indexes* of the items in sorted order, so `⍋30 10 20` gives `2 1 3`
* `(⍳X←⍴⍵)≡⍋⍵:⍵` Store the length of input list in X. If range `[1..X]` is equal to the sorted index order, the list is sorted, so return it.
* `⋄∇⍵[X?X]`: if this is not the case, recurse with shuffled array.
[Answer]
## Ruby - 33 characters
```
g=->l{l.shuffle!!=l.sort ?redo:l}
```
[Answer]
### *Mathematica*, ~~40~~ 37
```
NestWhile[RandomSample,#,Sort@#!=#&]&
```
With whitespace:
```
NestWhile[RandomSample, #, Sort@# != # &] &
```
[Answer]
## J - 34 27
```
f=:({~?~@#)^:(1-(-:/:~))^:_
```
eg:
```
f 5 4 1 3 2
1 2 3 4 5
f 'hello'
ehllo
```
The **{~ ?~@#** part shuffles the input:
```
({~ ?~@#) 1 9 8 4
4 8 9 1
({~ ?~@#) 'abcd'
bdca
```
[Answer]
## Python 61
Sorts in place.
```
import random
def f(l):
 while l!=sorted(l):random.shuffle(l)
```
[Answer]
# Python 94
```
from itertools import*
def f(a):return [x for x in permutations(a) if x==tuple(sorted(a))][0]
```
Other python answers use random.shuffle(). The documentation of the python random module states: 
> 
> Note that for even rather small len(x), the total number of
>  permutations of x is larger than the period of most random number
>  generators; this implies that most permutations of a long sequence can
>  never be generated.
> 
> 
> 
[Answer]
# K, 31 25
`{while[~x~x@<x;x:x@(-#x)?#x];x}`
```
{x@(-#x)?#x}/[{~x~x@<x};]
```
.
```
k){x@(-#x)?#x}/[{~x~x@<x};] 3 9 5 6 7 9 1
`s#1 3 5 6 7 9 9
```
.
```
k){x@(-#x)?#x}/[{~x~x@<x};] "ascsasd"
`s#"aacdsss"
```
[Answer]
## Python (69 chars)
```
from random import*
def f(a):
 while a>sorted(a):shuffle(a)
 return a
```
Sorts integers in increasing numeric order.
Note that recursive solutions, like
`from random import*;f=lambda a:a>sorted(a)and(shuffle(a)or f(a))or a`
will fail due to stack overflow for even small inputs (say N>5), because Python does not do tail-call optimisation.
[Answer]
# D without custom comparator: 59 Characters
```
R f(R)(R r){while(!isSorted(r))r.randomShuffle();return r;}
```
More Legibly:
```
R f(R)(R r)
{
    while(!r.isSorted)
        r.randomShuffle();
    return r;
}
```
# D with custom comparator: 69 Characters
```
R f(alias p,R)(R r){while(!isSorted!p(r))r.randomShuffle();return r;}
```
More Legibly:
```
R f(alias p, R)(R r)
{
    while(!isSorted!p(r))
        r.randomShuffle();
    return r;
}
```
[Answer]
### Scala 73:
```
def s(l:Seq[Int]):Seq[Int]=if(l==l.sorted)l else s(util.Random.shuffle l)
```
In Scala, we can check whether the compiler did a tail-call optimization:
```
@annotation.tailrec
def s(l:Seq[Int]):Seq[Int]=if(l==l.sorted)l else s(util.Random shuffle l)
```
and yes, it did. However, for a short List of 100 values:
```
val rList = (1 to 100).map(x=>r.nextInt (500))
s(rList) 
```
took nearly 4 months to complete. ;)
[Answer]
**C# (184 chars)**
```
T[]S<T>(T[]i)where T:IComparable<T>{T l=default(T);while(!i.All(e=>{var r=e.CompareTo(l)>=0;l=e;return r;})){i=i.OrderBy(a=>Guid.NewGuid()).ToArray();l=default(T);}return i.ToArray();}
```
It's not really nice to do this in C#. You have to support generics to support both value and reference types. There is no array shuffle function or function to check if something is sorted. 
Does anybody got any tips to make this better?
Edit
Version that only sorts int (134 chars):
```
int[]S(int[]i){var l=0;while(!i.All(e=>{var r=e>=l;l=e;return r;})){i=i.OrderBy(a=>Guid.NewGuid()).ToArray();l=0;}return i.ToArray();}
```
[Answer]
# GNU/BASH 65
```
b(){ IFS=$'\n';echo "$*"|sort -C&&echo "$*"||b $(shuf -e "$@");}
```
[Answer]
## C++11, 150 characters
```
#include<deque>
#include<algorithm>
void B(std::deque &A){while(!std::is_sorted(A.begin(),A.end())std::random_shuffle(myvector.begin(),myvector.end());}
```
Just.. made for fun.
[Answer]
# C++14, 158 bytes
```
#include <algorithm>
#include <random>
[](int*a,int s){std::random_device r;for(std::knuth_b g(r());!std::is_sorted(a,a+s);std::shuffle(a,a+s,g));return a;};
```
[Answer]
## Python - 61 chars
Recursive
```
from random import*;f=lambda l:l==sorted(l)or shuffle(l)>f(l)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~85~~ ~~82~~ ~~56~~ ~~55~~ 52 bytes
-26 bytes thanks to mazzy's suggestions  
-1 byte thanks to AdmBorkBork  
-3 bytes thanks to mazzy
```
for($l=$args;"$l"-ne($l|sort)){$l=$l|sort{random}}$l
```
[Try it online!](https://tio.run/##JclNCoAgEEDhvaeIGCphWtjPKjyMkNZiyhiDFubZrWj5vnf4y3JYLVEGp2N2nhsgDYaXMJVAZbvbF@7g@ZQyfuuPyGaf/ZYSUBZJiApc0SjssMcBRynq@qfxpQEV9jI/ "PowerShell – Try It Online")
PowerShell does have a relatively cheap array comparison by casting them to strings and comparing that. 
[Answer]
# [Go 1.20+](https://go.dev), 95 bytes
```
import(."math/rand";."sort")
func f[T Interface](I T){for!IsSorted(I){Shuffle(I.Len(),I.Swap)}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZZDPSsQwEMbvfYoxpwRixX8g6j7AgAeheytFYjfZ7domJUkRCX0SL0XwIXwTfRuTdhHRS2bm4_t9meT1bWumj17UT2IroRONzpquN9bnRHWevA9eHV99PSwazUkn_O7ECr0hNzlxUSMsU4OuQZVrQO2lVaKWFUVYs6CMPUJXRJfcUGSh2A1KtZJific1ZRzz4ln0bBwP13z6l15Co72DsoplSY5ZSWIwQ6mHYKUfrIY2KsjGfz7naMNhn2YGj8a0PwSWTXWL5b76C6VNfkEhGXkyrtLB0zhmC5N-KS4SMizgejXz4YJf8nN-xk9jLsWCZfc26q2e-8P7pmmp3w)
Expects input to implement [`sort.Interface`](https://pkg.go.dev/sort#Interface), which wants:
* `Len() int`: gets the number of elements.
* `Less(i, j int) bool`: checks whether the element at index `i` is less than the element at index `j`.
* `Swap(i, j int)`: swaps elements at indexes `i` and `j`.
Why is this `1.20+`? See below.
### [Go](https://go.dev), 158 bytes, seeded ints (pre-1.20)
```
import(."math/rand";."sort";."time")
func f(I[]int)[]int{Seed(Now().Unix())
for!IntsAreSorted(I){Shuffle(len(I),func(i,j int){I[i],I[j]=I[j],I[i]})}
return I}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LU_BisIwFLz3K7I5vUCsuO6CIB485iJC8VR6CJpotHmVmKJQ-iWClAU_wk_xbzZpvbxh5r0Z5t3_9lX3OsvtSe4VsdJgYuy5cj6l2nr6rL0ezd6PQYOUWukPYydxR-cpvQQtojdWUZboGrdEg8gLg571s8mU2sGqugJLN2huwMJZ5b4E-svSqSwEhL1gTXaotS4VlAoD5TEKDD-SmNSI3BRc5MdiEQePtGVt4pSvHRLRflr2rv4HYKRJ1i6YSwQNQ5Uf_sun_JtP2lDi4-m6Af8B)
### [Go](https://go.dev), 131 bytes, unseeded ints (pre-1.20), truly random (post-1.20)
```
import(."math/rand";."sort")
func f(I[]int)[]int{for!IntsAreSorted(I){Shuffle(len(I),func(i,j int){I[i],I[j]=I[j],I[i]})}
return I}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY4_CoMwGMX3nCLNlEBq6T8olA4dsxUcxSFoYmNNlJhM4tRjdJFCD9Gj9DY16vI-3uP9-N7rXdTDt-HZgxcCaq4MULqprYuQ1A59vJPr0-85ZzhCmrv7xnKTo3OE2jFDBEhvMigxS1JlHJm0k7VdMePaqxXx2BI5ZqSL717KSuBKmNHSwGFFSxiwjiUqpSwp00sQGmxPemCF89ZA1i9TJmoaignswM2OcGWwxPPfAz3SPd3RbU8IWJhhmO8f)
This solution is marked as both "unseeded" and "truly random" due to a change in Go v1.20 that changed the global, [default random number generator to be seeded "randomly"](https://tip.golang.org/doc/go1.20#:%7E:text=The%20math/rand%20package%20now%20automatically%20seeds%20the%20global%20random%20number%20generator) rather than be default, deterministic `rand.Seed(1)` in pre-1.20 versions.
[Answer]
# JavaScript, ~~98~~ 92 chars
More precisely ECMAScript 2015 (ES6)
**Minified:**
```
let b=r=>{for(;!r.every((o,t)=>o==[...r].sort()[t]);)r.sort(()=>Math.random()-.5);return r};
```
**Invocation:** `console.log(b([3, 2, 1, 5, 67, 4, 6, 5, 6, 4]))`
**Not minified:**
```
let bogoSort = (myArray) => {
  while (!myArray.every((v, i) => v == [...myArray].sort()[i])) {      
    myArray.sort(() => Math.random() -0.5)    
  }
  return myArray
}
```
**Explanation:**
* `myArray.every()` is an element-wise compare function. Comparing shuffled with sorted array
* `someArray.sort()` sorts in place so saving assignments, but also needs cloning for the sorted array
* `[...myArray]` clones the array ([array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment))
* `() => (Math.random() > .5) ? 1 : -1` is a custom compare function. Coin flip whether to order an element in front or behind
[Answer]
# Javascript 291 characters
min 
```
function f(e){var t=[].concat(e).sort();t.e=function(e){var n=true;t.forEach(function(t,r){if(t!=e[r])n=false});return n};while(!t.e(e.sort(function(){return Math.floor(Math.random()*2)?1:-1}))){console.log(e)}return e}
```
un-min
```
function f(a) {
var b = [].concat(a).sort();
b.e = function (z) {
    var l = true;
    b.forEach(function (v, i) {
        if (v != z[i]) l = false;
    });
    return l
};
while (!b.e(a.sort(function () {
    return Math.floor(Math.random() * 2) ? 1 : -1;
}))) {
    console.log(a);
}
return a;
}
```
[Answer]
# Python, 71 characters
```
from random import*
def b(l):
 while l!=sorted(l):shuffle(l)
 return(l)
```
Not the shortest one, but it works.
Ungolfed:
```
from random import *
def bogosort(list):
    while list != sorted(list):
        shuffle(list)
    return(list)
```
**Usage:**
Input: `b([1, 7, 3, 9, 2])`
Output: `[1, 2, 3, 7, 9]`
[Answer]
# Matlab, 59 bytes
Relatively straight forward approach:
```
x=input('');while~issorted(x);x=x(randperm(numel(x)));end;x
```
[Answer]
# J, 22 bytes
```
$:@({~?~@#)`]@.(-:/:~)
```
This is a recursive, tacit monad using an agenda. Here's how it works:
Let `y` be our list. First, the verb on the right of the agenda is `-:/:~`. This a verb graciously provided by [Leaky Nun](http://chat.stackexchange.com/transcript/message/30115841#30115841). It matches (`-:`) whether or not the input is sorted (`/:~`) using a monadic hook. (`(f g) y = y f (g y)`) This returns a one or a zero accordingly. The left hand side of the agenda is a gerund of two verbs: on the right is the identity verb `]`, and on the left is where the recursion takes place. The agenda selects either the identity verb at position `1` if the list *is* sorted, and the longer verb at position `0` if the list *isn't* sorted.
`$:@({~?~@#)` calls `$:` (the longest verb it is contained in) atop the result of `{~?~@#` on `y`. This shuffles the list, as `?~@#` takes the permutations of the length of `y`, being randomly-sorted indices of `y`. `{~`, in a monadic hook, returns a list from `y` whose indices are the right arg. This shuffled list is then called again with the agenda, and repeats until it is sorted.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes, language postdates challenge
```
ẊŒ¿’$¿
```
[Try it online!](https://tio.run/nexus/jelly#ASUA2v//4bqKxZLCv@KAmSTCv////1s1LDEsMCw0LDdd9W5vLWNhY2hl "Jelly – TIO Nexus")
## Explanation
```
ẊŒ¿’$¿
     ¿  While
 Œ¿’$     the input is not in its earliest possible permutation (i.e. sorted)
Ẋ       shuffle it
```
`Œ¿` assigns a number to each permutation of a list; 1 is sorted, 2 has the last two elements exchanged, etc., up to the factorial of the list length (which is the list in reverse order). So for a sorted list, this has the value 1, and we can decrement it using `’` in order to produce a "not sorted" test that's usable as a Boolean in a while loop condition. The `$` is to cause the condition to parse as a group.
[Answer]
# C++, 166 bytes
Meh.
```
#import<algorithm>
#import<random>
#define r b.begin(),b.end()
template<class v>
v f(v b){auto a=std::mt19937();while(!std::is_sorted(r))std::shuffle(r,a);return b;}
```
This should work on all STL containers that have `begin()` and `end()`.
Ungolfed:
```
#include <algorithm>
#include <random>
template <class v>
v f(v b) {
    auto a = std::mt19937();
    while (!std::is_sorted(b.begin(),b.end()))
        std::shuffle(b.begin(),b.end(),a);
    return b;
}
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 15 bytes
```
(?⍨∘≢⊇⊢)⍣{⍺≡∧⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/X8P@Ue@KRx0zHnUuetTV/qhrkeaj3sXVj3p3Pepc@KhjOZBR@z/tUduER719j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv8HaswFqgIZZsaVppALAA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
∈&ṣ≤₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v@POjrUHu5c/KhzCZD7/3@0kY6xjoGOqY5hLAA "Brachylog – Try It Online")
When I first saw ais523's Brachylog answer (as opposed to his Jelly answer, because if I'm not mistaken user62131 was also him), I wondered, what if it used backtracking instead of recursion? So at first, I tried `ṣ≤₁`. Turns out, since choosing something at random doesn't produce multiple outputs so much as it just produces one output nondeterministically, the shuffle predicate `ṣ` can't be backtracked to, so running that will simply fail unless you're lucky enough to shuffle it right on the first try. After that, I tried `pṣ≤₁`, which worked most of the time, but since a finitely long list has finitely many permutations, it still failed at random sometimes. After having abandoned the goal of achieving length reduction, I finally came up with this:
```
         The input
∈        is an element of
         an unused implicit variable,
 &       and the input
  ṣ      shuffled randomly
   ≤₁    which is increasing
         is the output.
```
[(Demonstration of randomness)](https://tio.run/##SypKTM6ozMlPN/r//1FHh9rDnYurH@7qVKt91LnkUVPj///RRjrGOgY6pjqGsQA)
Although it actually can be a bit shorter if we take some liberties with I/O...
# [Brachylog](https://github.com/JCumin/Brachylog), 4 bytes
```
⊆ṣ≤₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/qG3Do6bG8v@Putoe7lz8qHMJkPf/f7SRjrGOmY6pjmEsAA "Brachylog – Try It Online")
In order for the output to be useful, the input must not contain any duplicate elements, because in addition to sorting the input, this bogosort predicate adds in a random number of duplicate elements and zeroes. (Hypothetically, it could add in anything, but it just kind of doesn't.) Ordinarily I wouldn't bother mentioning something so far from correctly functioning, but I feel it's in the spirit of the challenge.
```
⊆        An ordered superset of the input
 ṣ       shuffled randomly
  ≤₁     which is increasing
         is the output.
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 28 bytes
```
{({.pick(*)}...~.sort).tail}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WqNaryAzOVtDS7NWT0@vTq84v6hEU68kMTOn9n9xYqVCmkK0oY6xjlGs9X8A "Perl 6 – Try It Online")
Anonymous code block that shuffles the list until it is sorted. Note that it sorts the list at least once, which is allowed. And no, the `{.pick(*)}` can't be replaced with `*.pick(*)`
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
Wn=Q.SQSQ;Q
```
Pretty happy with this, probably can be golfed a bit more
# Explanation
```
Wn=Q.SQSQ;Q
W    While
  =Q.SQ    Variable Q (input variable) shuffled 
 n  Does not equal
       SQ    Variable Q sorted
             ;  Do nothing (loop ends)
              Q    And output variable Q
```
[Try it online!](https://tio.run/##K6gsyfj/PzzPNlAvODA40Drw//9oCx0zHZNYAA "Pyth – Try It Online")
]