Skip to content

Commit 7a3b54c

Browse files
committed
Added the bogosort algorithm.
1 parent cedbe13 commit 7a3b54c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Sorts/bogoSort.js

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
* A simple helper function that checks, if the array is
3+
* sorted in ascending order.
4+
*/
5+
Array.prototype.isSorted = function() {
6+
7+
var length = this.length;
8+
9+
if (length < 2) {
10+
11+
return true;
12+
}
13+
14+
for (var i = 0; i < length - 1; i++) {
15+
16+
if (this[i] > this[i + 1]) {
17+
18+
return false;
19+
}
20+
}
21+
return true;
22+
};
23+
24+
/*
25+
* A simple helper function to shuffle the array randomly in place.
26+
*/
27+
Array.prototype.shuffle = function() {
28+
29+
for (var i = this.length; i; i--) {
30+
31+
var m = Math.floor(Math.random() * i);
32+
var n = this[i - 1];
33+
this[i - 1] = this[m];
34+
this[m] = n;
35+
}
36+
37+
};
38+
39+
/*
40+
* Implementation of the bogosort algorithm. This sorting algorithm randomly
41+
* rearranges the array until it is sorted.
42+
* For more information see: https://en.wikipedia.org/wiki/Bogosort
43+
*/
44+
function bogoSort(items) {
45+
46+
while(!items.isSorted()){
47+
48+
items.shuffle()
49+
}
50+
return items;
51+
}
52+
53+
//Implementation of bogoSort
54+
55+
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
56+
//Array before Sort
57+
console.log(ar);
58+
bogoSort(ar);
59+
//Array after sort
60+
console.log(ar);

0 commit comments

Comments
 (0)