forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BogoSort.java
54 lines (44 loc) · 1.31 KB
/
BogoSort.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
47
48
49
50
51
52
53
54
public class BogoSort {
public static int[] bogoSort(int[] vector) {
// Check if the vector is ordered
while (!isSorted(vector)) {
// Shuffle the vector to try to sort it randomly
shuffle(vector);
}
return vector;
}
/** Check if the vector is ordered */
private static boolean isSorted(int[] vector) {
for (int i = 0; i < (vector.length - 1); ++i) {
if (vector[i] > vector[i + 1]) {
return false;
}
}
return true;
}
/** Shuffle the vector to try to sort it randomly */
private static void shuffle(int[] vector) {
for (int x = 0; x < vector.length; ++x) {
int index1 = (int) (Math.random() * vector.length),
index2 = (int) (Math.random() * vector.length);
int a = vector[index1];
vector[index1] = vector[index2];
vector[index2] = a;
}
}
public static void printVector(int vector[]) {
for (int i = 0; i < vector.length; i++) {
System.out.print(vector[i] + ", ");
}
System.out.println("");
}
public static void main(String[] args) {
int vector[] = {9, 0, 4, 2, 3, 8, 7, 1, 6, 5};
System.out.println("BogoSort:");
System.out.println("Unordered vector:");
printVector(vector);
vector = bogoSort(vector);
System.out.println("Sorted vector:");
printVector(vector);
}
}