62,614
社区成员
发帖
与我相关
我的任务
分享
//用线程不复杂
public class Test implements Runnable {
public static void main(String[] args) {
int[] d = new int[]{
1, 3, 2, 9, 5, 6, 7, 8, 4
};
Test t = new Test(d);
t.start();
}
private boolean init;
private boolean push;
private boolean end;
private Thread thr = new Thread(this);
private int[] date;
public Test(int date[]) {
this.date = date;
}
/**开始排序*/
public void start() {
if (init) {
return;
}
init = true;
thr.start();
}
/**返回当前排序的状态*/
public String Context() {
String str = "[";
synchronized (date) {
if (date != null) {
for (int i = 0; i < date.length; i++) {
str += date[i];
if (i + 1 < date.length) {
str += ",";
}
}
}
}
return str + "]";
}
/**暂停,恢复*/
public void push() {
push = !push;
}
/**是不是排序结束*/
public boolean isEnd() {
return end;
}
private java.util.Stack<Operator> s = new java.util.Stack<Operator>();
public void run() {
s.add(new Operator(0, date.length - 1));
while (!s.isEmpty()) {
while (push) {
try {
Thread.sleep(0);
} catch (InterruptedException ex) {
}
}
Operator wp = s.pop();
int i = wp.l;
int j = wp.r;
if (i < j) {
//默认左边第一个数为比较的 key
int key = date[wp.l];
//排序
do {
//找到左边边界
while (date[i] < key && i < wp.r) {
i++;
}
//找到右边边界
while (date[j] > key && j > wp.l) {
j--;
}
// 左边大的 和 右边小的 交换
if (i < j) {
synchronized (date) {
int temp = date[i];
date[i] = date[j];
date[j] = temp;
}
}
} while (i < j);
//比较结束
if (i > j) {
synchronized (date) {
int temp = date[wp.l];
date[wp.l] = date[j];
date[j] = temp;
}
}
//加入要比较的新区间
s.push(new Operator(wp.l, j - 1));
s.push(new Operator(j + 1, wp.r));
//System.out.println("过程:" + Context());
}
}
end = true;
}
class Operator {
int r;
int l;
Operator(int l, int r) {
this.l = l;
this.r = r;
}
}
}