Skip to content

Commit b78102d

Browse files
authored
Merge pull request #487 from SS010800/SS010800/bogo_sort
adding bogo sort
2 parents 5ab8548 + 894c9ee commit b78102d

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

java/sorting/bogo_sort.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// Java Program to implement BogoSort
2+
public class BogoSort
3+
{
4+
// Sorts array a[0..n-1] using Bogo sort
5+
void bogoSort(int[] a)
6+
{
7+
// if array is not sorted then shuffle the
8+
// array again
9+
while (isSorted(a) == false)
10+
shuffle(a);
11+
}
12+
13+
// To generate permutation of the array
14+
void shuffle(int[] a)
15+
{
16+
17+
for (int i=1; i <= n; i++)
18+
swap(a, i, (int)(Math.random()*i));
19+
}
20+
21+
// Swapping 2 elements
22+
void swap(int[] a, int i, int j)
23+
{
24+
int temp = a[i];
25+
a[i] = a[j];
26+
a[j] = temp;
27+
}
28+
29+
// To check if array is sorted or not
30+
boolean isSorted(int[] a)
31+
{
32+
for (int i=1; i<a.length; i++)
33+
if (a[i] < a[i-1])
34+
return false;
35+
return true;
36+
}
37+
38+
// Prints the array
39+
void printArray(int[] arr)
40+
{
41+
for (int i=0; i<arr.length; i++)
42+
System.out.print(arr[i] + " ");
43+
System.out.println();
44+
}
45+
46+
public static void main(String[] args)
47+
{
48+
//Enter array to be sorted here
49+
int[] a = {3, 2, 5, 1, 0, 4};
50+
BogoSort ob = new BogoSort();
51+
52+
ob.bogoSort(a);
53+
54+
System.out.print("Sorted array: ");
55+
ob.printArray(a);
56+
}
57+
}
58+

0 commit comments

Comments
 (0)