8000 Merge pull request #36 from mashawan/BogoSort · sonwanigaurav/Java-Algorithms@dcef18b · GitHub
[go: up one dir, main page]

Skip to content

Commit dcef18b

Browse files
authored
Merge pull request darpanjbora#36 from mashawan/BogoSort
Added a Java implementation of Bogosort.
2 parents d8beabb + fd379b3 commit dcef18b

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Sorting Algorithms/BogoSort.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.Arrays;
2+
import java.util.Random;
3+
4+
/**
5+
* Java Implementation of the Bogo Sort (a highly inefficient sorting algorithm based on the generate and test paradigm.)
6+
* See: https://en.wikipedia.org/wiki/Bogosort
7+
*/
8+
class BogoSort {
9+
10+
public static void bogoSort(int arr[]) {
11+
int counter = 0;
12+
while (!test(arr)) {
13+
shuffle(arr);
14+
counter++;
15+
}
16+
System.out.println("SUCCESS! (After " + counter + " shuffles");
17+
System.out.println(Arrays.toString(arr));
18+
}
19+
20+
private static void shuffle(int arr[]) {
21+
final Random random = new Random();
22+
for (int i = 0; i < arr.length; i++) {
23+
final int value = arr[i];
24+
final int indexToSwapWith = random.nextInt(arr.length);
25+
final int valueToSwapWith = arr[indexToSwapWith];
26+
arr[i] = valueToSwapWith;
27+
arr[indexToSwapWith] = value;
28+
}
29+
}
30+
31+
private static boolean test(int arr[]) {
32+
for (int i = 0; i < arr.length - 1; i++) {
33+
int value = arr[i];
34+
int nextValue = arr[i + 1];
35+
if (value > nextValue) {
36+
return false;
37+
}
38+
}
39+
return true;
40+
}
41+
42+
public static void main(String[] args) {
43+
int[] testArray = new int[] {1, 4, 5, 2, 27, 19, 18};
44+
bogoSort(testArray);
45+
}
46+
}

0 commit comments

Comments
 (0)
0