Skip to content

Commit 61d10f1

Browse files
committed
Added bogo sort
1 parent 07e254f commit 61d10f1

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

classical_algorithms/c++/bogosort.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
//Bogo sort (AKA slow sort,random sort, monkey sort, estou com sort) is an algorithm based on the random sorting of elements. Although it's not actually used in practice, it's a good tool to teach about more efficient algorithms.
5+
//Heads-up note: the algorithm will certainly run for a very (very!) long time if you try to sort too many elements, 10 is already a good deal.
6+
7+
//Algorithm:
8+
bool isSorted(int array[], int n){
9+
while(n-1 > 0){
10+
n--;
11+
if(array[n] < array[n-1]){
12+
return false;
13+
}
14+
}
15+
return true;
16+
}
17+
18+
void shuffle(int array[], int n){
19+
for(int i=0; i < n; i++){
20+
swap(array[i], array[rand()%n]);
21+
}
22+
}
23+
24+
void bogoSort(int array[], int n){
25+
while(!isSorted(array, n)){
26+
shuffle(array, n);
27+
}
28+
}
29+
30+
//Test:
31+
int main(){
32+
int n;
33+
int array[] = {3, 1, 4, 5, 8, 7, 9, 2, 10, 6};
34+
n = sizeof(array) / sizeof(array[0]);
35+
cout << "Elements before bogo sort:\n";
36+
for (int i = 0; i < n; i++){
37+
cout << array[i] << " ";
38+
}
39+
cout << "\n";
40+
41+
bogoSort(array, n);
42+
43+
cout << "Elements after bogo sort:\n";
44+
for(int i = 0; i < n; i++){
45+
cout << array[i] << " ";
46+
}
47+
cout << "\n";
48+
}

readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ Code | Test
4949
[0/1 Knapsack Problem](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/01_knapsack_problem.cpp) | Missing tests
5050
[Kadane's Algorithm](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Kadane_Algorithm.cpp) | Missing tests
5151
[Topological Sort](https://github.com/ErR0rpj/code_problems/blob/master/classical_algorithms/c%2B%2B/Topological_sort.cpp) | Missing Tests
52+
[Bucket Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/bucketsort.cpp) | Missing tests
53+
[Bogo Sort](https://github.com/larissalages/code_problems/blob/master/classical_algorithms/c%2B%2B/bogosort.cpp) | Missing tests
5254

5355
# Codeforces
5456

0 commit comments

Comments
 (0)