简单地说,我在java中开发一个代码,用于将20个大小的数组分成4个部分,其中这4个线程将一起运行以堆排序5个元素(线程1排序索引0-4,线程2排序索引5-9等等)最后将它们与合并排序技术合并在一起。 合并排序工作完全正常,因此我不包括它。 但堆排序功能无法提供正确的答案。 线程在数组的14到19的索引中保持旋转。 我在这里做错了吗?
class heapsort
{
private static int[] a;
private static int i;
private static int left;
private static int right;
private static int largest;
public static void maxheap(int[] a, int i,int n00,int n01)
{
left = 2 * i;
right = 2 * i + 1;
if ((left >= n00 && left <=n01) && a[left] > a[i])
{
largest = left;
}
else
{
largest = i;
}
if ((right >= n00 && right <=n01) && a[right] > a[largest])
{
largest = right;
}
if (largest != i)
{
int t = a[i];
a[i] = a[largest];
a[largest] = t;
heapsort h1=new heapsort();
h1.maxheap(a, largest,n00,n01);
}
}
}
class sorter_ss extends Thread
{
private static int n1,n2,n;
private static int a[];
sorter_ss(int a0[],int i1, int i2)
{
a=a0; n1=i1; n2=i2;
}
public void run()
{
//build heap function
int n3=(n2+n1)/2;
for (int i = n3; i >= n1; i--)
{
heapsort h1=new heapsort();
h1.maxheap(a,i,n1,n2);
}
//heapsort function
for (int i = n2-1; i >= n1; i--)
{
int t = a[i];
a[i] = a[n1];
a[n1] = t;
heapsort h2=new heapsort();
h2.maxheap(a,i,n1,n2);
}
}
}
public class testheap
{
public static void main(String[] args)
{
int[] a2 = { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7, 80, 76, 34, 23, 56, 90, 99, 321, 86, 75};
caller(a2);
}
public static void caller(int a1[])
{ int t[]=new int[100];
System.out.println("Array is : \n");
for (int i = 0; i < a1.length; i++)
{
System.out.print(a1[i] + " ");
} System.out.println();
try{
sorter_ss s1=new sorter_ss(a1,0,4);
sorter_ss s2=new sorter_ss(a1,5,9);
sorter_ss s3=new sorter_ss(a1,10,14);
sorter_ss s4=new sorter_ss(a1,15,19);
s1.start();
s2.start();
s3.start();
s4.start();
s1.join();
s2.join();
s3.join();
s4.join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Sorted Array is : \n");
for (int i = 0; i < a1.length; i++)
{
System.out.print(a1[i] + " ");
} System.out.println();
}
}
答案 0 :(得分:0)
您最基本的问题是您使用static
来声明线程的字段。你永远不应该这样做。
sorter_ss s1=new sorter_ss(a1,0,4);
sorter_ss s2=new sorter_ss(a1,5,9);
sorter_ss s3=new sorter_ss(a1,10,14);
sorter_ss s4=new sorter_ss(a1,15,19);
基本上你的4个线程只会在15-19个索引之间运行,因为你最后设置它们。
当你解决这个问题时,请看看Fork / Join,它是专门创建的:
http://www.oracle.com/technetwork/articles/java/fork-join-422606.html