Skip to content

Commit 8717d61

Browse files
committed
Add bogo sort
1 parent e44016c commit 8717d61

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

Sorts/BogoSort.java

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package Sorts;
2+
3+
import java.util.Random;
4+
5+
public class BogoSort {
6+
private static <T> void swap(T array[], int first, int second){
7+
T randomElement = array[first];
8+
array[first] = array[second];
9+
array[second] = randomElement;
10+
}
11+
12+
private static <T extends Comparable<T>> boolean isSorted(T array[]){
13+
for(int i = 0; i<array.length-1; i++){
14+
if(array[i].compareTo(array[i+1]) > 0) return false;
15+
}
16+
return true;
17+
}
18+
19+
// Randomly shuffles the array
20+
private static <T> void nextPermutation(T array[]){
21+
int length = array.length;
22+
Random random = new Random();
23+
24+
for (int i = 0; i < array.length; i++) {
25+
int randomIndex = i + random.nextInt(length - i);
26+
swap(array, randomIndex, i);
27+
}
28+
}
29+
30+
public static <T extends Comparable<T>> void bogoSort(T array[]) {
31+
while(!isSorted(array)){
32+
nextPermutation(array);
33+
}
34+
}
35+
36+
// Driver Program
37+
public static void main(String[] args)
38+
{
39+
// Integer Input
40+
int[] arr1 = {4,23,6,78,1,54,231,9,12};
41+
int last = arr1.length;
42+
Integer[] array = new Integer[last];
43+
for (int i=0;i<last;i++) {
44+
array[i] = arr1[i];
45+
}
46+
47+
bogoSort(array);
48+
49+
// Output => 1 4 6 9 12 23 54 78 231
50+
for(int i=0; i<last; i++)
51+
{
52+
System.out.print(array[i]+"\t");
53+
}
54+
System.out.println();
55+
56+
// String Input
57+
String[] array1 = {"c", "a", "e", "b","d"};
58+
last = array1.length;
59+
60+
bogoSort(array1);
61+
62+
//Output => a b c d e
63+
for(int i=0; i<last; i++)
64+
{
65+
System.out.print(array1[i]+"\t");
66+
}
67+
}
68+
}

0 commit comments

Comments
 (0)