首页 > 编程语言 > 详细

java算法之猴子排序睡眠排序

时间:2020-10-13 10:19:44      阅读:59      评论:0      收藏:0      [点我收藏+]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class A {
private volatile int anInt = 0;
private volatile int jkl = 0;
public static void main(String[] args) {
A a = new A();
Integer[] integers0 = {5,4,7,1,9,3,8,2,0};
List<Integer> integers0s = a.sleepSort(Arrays.asList(integers0));
while (true){
if (a.anInt == integers0.length){
System.err.println("睡眠排序:" + integers0s);
break;
}
}

Integer[] integers1 = {5,4,7,1,-9};
Integer[] integers2 = {5,4,7,1,-9,-3};
Integer[] integers3 = {5,4,7,1,-9,-3,8};
Integer[] integers4 = {5,4,7,1,-9,-3,8,2};
Integer[] integers5 = {5,4,7,1,-9,-3,8,2,3};
List<Integer[]> list = new ArrayList<>();
list.add(integers1);
list.add(integers2);
list.add(integers3);
list.add(integers4);
list.add(integers5);
int i = 1;
for (Integer[] integers : list) {
long start = System.currentTimeMillis();
A aa = new A();
while (true){
List<Integer> bogoSort = a.bogoSort(Arrays.asList(integers));
if (aa.isSort(bogoSort)){
System.err.println(bogoSort);
break;
}
//System.out.println(bogoSort);
}
long end = System.currentTimeMillis();
System.err.println("integers" + i++ + "耗时:" + (end - start) + "毫秒");
}


}
public List<Integer> sleepSort(List<Integer> list) {
List<Integer> result = new ArrayList<>();
for (Integer integer : list) {
new Thread(() -> {
try {
Thread.sleep(integer);
result.add(integer);
anInt++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
}
return result;
}

public List<Integer> bogoSort(List<Integer> list) {
jkl = 0;
List<Integer> result = new ArrayList<>();
for (Integer integer : list) {
new Thread(()->{
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (result){
result.add(integer);
jkl ++;
}
}).start();
}
while (true){
if (jkl == list.size())
return result;
}
}
public boolean isSort(List<Integer> list){
Integer i = list.get(0);
for (Integer integer : list) {
if (integer < i){
return false;
}
i = integer;
}
return true;
}
}

睡眠的精度不知道还有没有什么优化的办法?

java算法之猴子排序睡眠排序

原文:https://www.cnblogs.com/bzdofj/p/13806887.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!