forked from mrizky-kur/Redux-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BogoSort.java
47 lines (38 loc) · 979 Bytes
/
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
public class BogoSort {
void bogoSort(int[] a) {
while (isSorted(a) == false) {
shuffle(a);
}
}
void shuffle(int[] a) {
for (int i = 0; i < a.length; i++) {
swap(a, i, (int) (Math.random() * i));
}
}
void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
boolean isSorted(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) {
return false;
}
}
return true;
}
void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
int[] a = {3, 2, 5, 1, 0, 4};
BogoSort ob = new BogoSort();
ob.bogoSort(a);
System.out.print("Sorted array: ");
ob.printArray(a);
}
}