猴子排序(Bogosort)定义是通过不断随机地重新排列数组元素,直到数组被意外地排序成正确的顺序为止。 之所以叫猴子排序是指如果让一只猴子在纸上涂鸦,只要尝试足够多的次数,也可以写出一部三国演义。
以下是猴子排序的代码
import java.util.ArrayList;
import java.util.List;
public class MKTest {
public static void main(String[] args) {
List<Integer> aList = RandomIntegerUtils.getRandomIntegers(0, 100, 10);
System.out.println(aList);
long st = System.currentTimeMillis();
List<Integer> sortList = mkSort(aList);
System.out.println(System.currentTimeMillis() - st);
System.out.println(sortList);
}
private static List<Integer> mkSort(List<Integer> list) {
while (true){
//随机打乱顺序
int size = list.size();
List<Integer> indexRandomList = RandomIntegerUtils.getRandomIntegers(0, size, size);
List<Integer> sortList = new ArrayList<>();
for (Integer index : indexRandomList) {
Integer value = list.get(index);
sortList.add(value);
}
//判断打乱后顺序是否正确
Integer lastValue = null;
boolean sort = true;
for (Integer value : sortList) {
if (lastValue != null && lastValue > value){
sort = false;
break;
}
lastValue = value;
}
//顺序正确则返回正确的顺序
if (sort){
return sortList;
}
}
}
}
下面是工具类中的RandomIntegerUtils的方法
/**
* 生成范围内随机整数, 范围[min, max)
* @param min 最小范围
* @param max 最大范围
* @return 随机整数
*/
public static int getRandomInteger(Integer min, Integer max){
if (min == null){
min = 0;
}
if (max == null){
max = 100;
}
if (min >= max ){
throw new RuntimeException("参数max值必须大于min值");
}
Random rand = new Random();
return min + rand.nextInt(max - min); // 生成随机整数
}
/**
* 生成count个指定范围的随机数
*/
public static List<Integer> getRandomIntegers(Integer min, Integer max, Integer count){
List<Integer> result = new ArrayList<>();
if (count == null || count <= 0){
return result;
}
if (min == null){
min = 0;
}
if (max == null){
max = 100;
}
if (min >= max ){
throw new RuntimeException("参数max值必须大于min值");
}
if (count > max - min){
throw new RuntimeException("参数count的最大值不能超过区间容纳的最多整数值");
}
for (int i = 0; i < count; i++) {
int num = getRandomInteger(min, max);
while (result.contains(num)){
num = getRandomInteger(min, max);
}
result.add(num);
}
return result;
}
运行main方法后, 将100内的十个随机数排序得到结果如图:
可以看出十个数的排序仅仅用了2秒左右, 速度还是蛮快的;
后面我改为十五个数测试一下,等了一会会会会会会儿, 下班时间到了, 结果还没有出来。
分析时间复杂度变化符合阶乘, 10个数排序次数期望是10!为3628800次, 如果是15个数测期望尝试次数为1307674368000次,如果10个是两秒的话,对比15个数则差不多要8.34天,当然如果您感觉自己是欧皇的话也可能一次就成功了,这样上限就是不到1毫秒,还蛮快的, 不过要是脸黑的话也可能永远不会排序成功。
50个数是30414093201713378043612608166064768844377641568960512000000000000次,不过对于欧皇您来说也可能一次就成功了,看来数字个数越多这个算法的潜力越大,综上所述可知,猴子排序仅仅在10个数字以内可以稳定的使用, 如果数字个数增加则排序时间呈阶乘方式飞速增长,不过对于欧皇的您来说这都不是事!