forked from algorithm-archivists/algorithm-archive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bogo.java
46 lines (36 loc) · 1.04 KB
/
bogo.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Bogo {
static void bogoSort(int[] arr) {
while(!isSorted(arr)) {
shuffle(arr);
}
}
static boolean isSorted(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
if(arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
static void shuffle(int[] arr) {
for (int r = arr.length - 1; r > 0; r--) {
int i = (int) Math.floor(Math.random() * r);
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
}
public static void main(String[] args) {
int[] test = new int[]{20, -3, 50, 1, -6, 59};
System.out.println("Unsorted array :");
for (int i = 0; i < test.length; i++) {
System.out.print(test[i] + " ");
}
bogoSort(test);
System.out.println("\n\nSorted array :");
for (int i = 0; i < test.length; i++) {
System.out.print(test[i] + " ");
}
System.out.println("");
}
}