我尝试使用fork join来修改合并排序。 我使用它作为fork / join示例,所以我需要保持基本。 我想编辑常规合并排序,以便当段大小低于101(100或更小)时,它将使用插入排序对该段进行排序,然后退出递归调用并开始将段合并回来。 排序只是根本不起作用。如果我改变调用和连接的顺序(以阻止其他代码运行),它工作正常,所以我假设它是因为我的排序同时运行,它是不正确的。 例如,如果我写 int mid =(lb + ub)/ 2; MergeInsertSortQ left = new MergeInsertSortQ(f,lb,mid); MergeInsertSortQ right = new MergeInsertSortQ(f,mid,ub); left.fork(); left.join(); right.fork(); right.join(); 合并(F,磅,中期,UB); 它排序很好,但这基本上是连续的,所以并不是我想要做的事情。
这是我正在使用的代码(包括主要的一点测试)
import java.util.concurrent。*;
公共类MergeInsertSortQ扩展了RecursiveAction {
private int[] f;
private int lb, ub;
public MergeInsertSortQ(int f[], int lb, int ub)
{
this.f = f;
this.lb=lb;
this.ub=ub;
}
protected void compute(){
//Insertion Sort performed when a segment of size
//100 or less is reached otherwise do merge sort
if(ub-lb>100)
{
int mid = (lb+ub)/2;
MergeInsertSortQ left = new MergeInsertSortQ(f,lb,mid);
MergeInsertSortQ right = new MergeInsertSortQ(f,mid,ub);
invokeAll(left,right);
left.join();
right.join();
merge(f,lb,mid,ub);
}
else if(ub-lb>=1)
{
for (int i = lb; i<ub;i++)
{
int temp = f[i];
int j = i-1;
while (j >= 0 && f[j] > temp)
{
f[j+1] = f[j];
j = j-1;
}
f[j+1] = temp;
}
}
}
protected void merge(int f[], int lower, int middle, int top){
int i = lower; int j = middle;
//use temp array to store merged sub-sequence
int temp[] = new int[top-lower]; int t = 0;
while(i < middle && j < top)
{
if(f[i] <= f[j])
{
temp[t]=f[i];i++;t++;
}
else{
temp[t] = f[j]; j++; t++;
}
}
//tag on remaining sequence
while(i < middle)
{
temp[t]=f[i]; i++; t++;
}
while(j < top)
{
temp[t] = f[j]; j++; t++;
}
//copy temp back to f
i = lower; t = 0;
while(t < temp.length)
{
f[i] = temp[t]; i++; t++;
}
}
public static void main(String[] args)
{
//Initialise & print array before sorting
int A[]=new int[200];
for(int j=0;j<A.length;j++)
{
A[j]=(int)(Math.random()*10000);
System.out.print(A[j]+" ");
}
System.out.println();
System.out.println("**********************************");
System.out.println();
// Do the sort
ForkJoinPool fjPool=new ForkJoinPool();
fjPool.invoke(new MergeInsertSortQ(A,0,A.length));
//Check if array sorted and print
boolean sorted=true;
for(int i=0;i<A.length-1;i++)
{
System.out.print(A[i] + " ");
if (A[i]>A[i+1])
{
System.out.println();
System.out.println(A[i]+" is greater than "+A[i+1]+", location "+i);
sorted=false;
//break;
}
}
System.out.println();
if (sorted) System.out.println("The array is sorted!!!");
else System.out.println("WARNING: The array is NOT SORTED");
}
}