8000 Merge pull request #20 from gastonche/sorting/bogosort · AllAlgorithms/javascript@982334e · GitHub
[go: up one dir, main page]

Skip to content

Commit 982334e

Browse files
authored
Merge pull request #20 from gastonche/sorting/bogosort
[sorting] added algorithim for bogo sort
2 parents c882198 + 0d8da48 commit 982334e

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

sorting/BogoSort.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
* In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms.
3+
*/
4+
5+
function Bogosort(arr){
6+
var isSorted = function(arr){
7+
for(var i = 1; i < arr.length; i++){
8+
if (arr[i-1] > arr[i]) {
9+
return false;
10+
}
11+
}
12+
return true;
13+
};
14+
15+
function shuffle(arr){
16+
var count = arr.length, temp, index;
17+
18+
while(count > 0){
19+
index = Math.floor(Math.random() * count);
20+
count--;
21+
22+
temp = arr[count];
23+
arr[count] = arr[index];
24+
arr[index] = temp;
25+
}
26+
27+
return arr;
28+
}
29+
30+
function sort(arr){
31+
var sorted = false;
32+
while(!sorted){
33+
arr = shuffle(arr);
34+
sorted = isSorted(arr);
35+
}
36+
return arr;
37+
}
38+
39+
return sort(arr);
40+
}
41+
42+
43+
var array = [3, 0, 2, 5, -1, 4, 1];
44+
console.log("Original Array Elements");
45+
console.log(array);
46+
console.log("Sorted Array Elements");
47+
console.log(Bogosort(array));

0 commit comments

Comments
 (0)
0