Bogosort
The well known Bogosort sorting algorithm for JavaScript
The algorithm
Bogosort, also known as Monkeysort or Stupidsort is a quite simple sorting algorithm rarely used in production.
The idea is to shuffle a collection as long as it is not sorted.
// Input: Arraywhile !
Shuffle
Bogosort uses a modern variant of the Fisher-Yates shuffle, also known as the Durstenfeld shuffle algorithm. It also relies on the broken Math.random().
// Input: Array of length nfor i from n − 1 to 1 do j = random from 0 to i exchange aj and ai
API
Bogosort is exposed via Universal Module Definition (UMD). Thus, you can use it in your browser, in a require.js environment as well as in node or any bundled project. At also comes with a minified version and a source map.
Bogosort exposes a function bogosort()
that takes an array of numbers and returns a sorted copy of it. The original array
will not be mutated.
var bogosort = ; var sorted = ;
The bogosort()
function also has a function property bogosort.measure()
that returns an object containing
the sorted collection as well as number of rounds it took to sort it.
var bogosort = ; var sorted = bogosort; console;console;
The example.js file contains an example of that.
Building it
To build it yourself just checkout the repository and run npm install
.
All important commands are run using npm
.
# Run tests npm test # Run the example npm start # Build the minified version npm run build