forked from VAR-solutions/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBogosort.java
More file actions
59 lines (52 loc) · 1.17 KB
/
Bogosort.java
File metadata and controls
59 lines (52 loc) · 1.17 KB
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
55
56
57
58
59
// Java Program to implement BogoSort
public class BogoSort
{
// Sorts array a[0..n-1] using Bogo sort
void bogoSort(int[] a)
{
// if array is not sorted then shuffle the
// array again
while (isSorted(a) == false)
shuffle(a);
}
// To generate permuatation of the array
void shuffle(int[] a)
{
// Math.random() returns a double positive
// value, greater than or equal to 0.0 and
// less than 1.0.
for (int i=1; i <= n; i++)
swap(a, i, (int)(Math.random()*i));
}
// Swapping 2 elements
void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// To check if array is sorted or not
boolean isSorted(int[] a)
{
for (int i=1; i<a.length; i++)
if (a[i] < a[i-1])
return false;
return true;
}
// Prints the array
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)
{
//Enter array to be sorted here
int[] a = {3, 2, 5, 1, 0, 4};
BogoSort ob = new BogoSort();
ob.bogoSort(a);
System.out.print("Sorted array: ");
ob.printArray(a);
}
}