快排
package p18.juc;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class ForkJoinDemo {
class FKQS extends RecursiveAction{
int [] arr;
int start;
int end;
FKQS(int[]arr,int start,int end){
this.arr = arr;
this.start = start;
this.end = end;
}
@Override
protected void compute() {
if(end - start>0) {
int L = start;
int R = end;
int temp = arr[L];
while(L!=R) {
while(R>L) {
if(arr[R]<temp) {
arr[L] = arr[R];
break;
}
R--;
}
while(L<R) {
if(arr[L]>temp) {
arr[R] = arr[L];
break;
}
L++;
}
}
arr[L]=temp;
FKQS segmentL = new FKQS(arr,start,L-1);
FKQS segmentR = new FKQS(arr,L+1,end);
segmentL.fork();
segmentR.fork();
segmentL.join();
segmentR.join();
}
}
}
public static void main(String[] args) {
int [] arr = {8,3,4,2,6,5,0,7,2};
RecursiveAction f = new ForkJoinDemo().new FKQS(arr,0,arr.length-1);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(f);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
二分查找
class FKSF extends RecursiveTask<Integer>{
int[]arr;
int L;
int R;
int target;
public FKSF(int [] arr,int L,int R,int target) {
this.arr = arr;
this.L = L;
this.R = R;
this.target = target;
}
@Override
protected Integer compute() {
if(R>=L) {
int mid = (R+L)/2;
if(target>arr[mid]) {
FKSF subTask = new FKSF(arr,mid+1,R,target);
subTask.fork();
return subTask.join();
}else if(target<arr[mid]) {
FKSF subTask = new FKSF(arr,L,mid-1,target);
subTask.fork();
return subTask.join();
}else {
return mid;
}
}else {
return Integer.valueOf(-1);
}
}
}
public static void main(String[] args) {
int [] arr = {1,3,4,5,7,11,20,33,50};
RecursiveTask<Integer> task = new FKSF(arr,0,arr.length-1,9);
ForkJoinPool pool = new ForkJoinPool();
int r =pool2.invoke(task);
System.out.println(r);
}