2018-11-14 01:15:47 +08:00
|
|
|
package Sorts;
|
2018-04-09 20:24:16 +08:00
|
|
|
|
|
|
|
import java.util.Random;
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @author Podshivalov Nikita (https://github.com/nikitap492)
|
|
|
|
* @see SortAlgorithm
|
|
|
|
*/
|
2018-04-10 02:14:40 +08:00
|
|
|
public class BogoSort implements SortAlgorithm {
|
2018-04-09 20:24:16 +08:00
|
|
|
|
|
|
|
private static final Random random = new Random();
|
|
|
|
|
|
|
|
|
2019-12-30 14:03:14 +08:00
|
|
|
private static <T extends Comparable<T>> boolean isSorted(T[] array) {
|
2019-05-09 19:32:54 +08:00
|
|
|
for (int i = 0; i < array.length - 1; i++) {
|
|
|
|
if (SortUtils.less(array[i + 1], array[i])) return false;
|
2018-04-09 20:24:16 +08:00
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Randomly shuffles the array
|
2019-12-30 14:03:14 +08:00
|
|
|
private static <T> void nextPermutation(T[] array) {
|
2018-04-09 20:24:16 +08:00
|
|
|
int length = array.length;
|
|
|
|
|
|
|
|
for (int i = 0; i < array.length; i++) {
|
|
|
|
int randomIndex = i + random.nextInt(length - i);
|
2018-11-14 01:15:47 +08:00
|
|
|
SortUtils.swap(array, randomIndex, i);
|
2018-04-09 20:24:16 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-30 14:03:14 +08:00
|
|
|
public <T extends Comparable<T>> T[] sort(T[] array) {
|
2019-05-09 19:32:54 +08:00
|
|
|
while (!isSorted(array)) {
|
2018-04-09 20:24:16 +08:00
|
|
|
nextPermutation(array);
|
|
|
|
}
|
|
|
|
return array;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Driver Program
|
|
|
|
public static void main(String[] args) {
|
|
|
|
// Integer Input
|
|
|
|
Integer[] integers = {4, 23, 6, 78, 1, 54, 231, 9, 12};
|
|
|
|
|
|
|
|
BogoSort bogoSort = new BogoSort();
|
|
|
|
|
|
|
|
// print a sorted array
|
2018-11-14 01:15:47 +08:00
|
|
|
SortUtils.print(bogoSort.sort(integers));
|
2018-04-09 20:24:16 +08:00
|
|
|
|
|
|
|
// String Input
|
2019-05-09 19:32:54 +08:00
|
|
|
String[] strings = {"c", "a", "e", "b", "d"};
|
2018-04-09 20:24:16 +08:00
|
|
|
|
2018-11-14 01:15:47 +08:00
|
|
|
SortUtils.print(bogoSort.sort(strings));
|
2018-04-09 20:24:16 +08:00
|
|
|
}
|
|
|
|
}
|