# λ Bogosort

======= Algorithm ======= <syntax js> function bogosort(a) { while (!isSorted(a)) { shuffle(a); } return a; } </syntax> ======= Support ======= <syntax js> function isSorted(a) { for (var i=a.length-1; i>0; i--) { if (a[i] < a[i-1]) { return false; } } return true; } function swap(a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; } function shuffle(a) { for (var i=a.length-1; i>0; i--) { // j is a random integer [0-i] var j = Math.floor(Math.random()*(i+1)); swap(a, j, i); } return a; } function run(a) { bogosort(a); } </syntax> ======= Tests ======= <syntax js> </syntax> ======= Options ======= <syntax js> { "title":"Bogosort", "height":"270px" } </syntax> ======= Visualisation ======= <syntax html> <html> <head> <link rel="stylesheet" type="text/css" href="algorithms-lib/graph.css"/> <script src="http://d3js.org/d3.v2.js"></script> <script src="algorithms-lib/graph.js"></script> <script type="text/javascript"> var graph = new Graph(5); window.onload = function() { chart = graph.createGraph(d3.select("#chart")) } function args(forCloning) { return forCloning? graph.getClonableArray() : graph.array; } function update(n, x, isRunning, duration, prev) { if (duration < 0) { return; // State-less visualisation. } if (x) { graph.drawGraph(duration); } } </script> </head> <body> <div style="position:absolute;padding:2px"> <button onclick="graph.randomise(200)">Random</button> <button onclick="graph.randomise(5)">Few Unique</button> <button onclick="graph.almostSorted()">Almost sorted</button> <button onclick="graph.reverse()">Reverse</button> </div> <div id="chart"></div> </body> </html> </syntax>