So briefly I am developing a code in java for dividing a 20 size array into 4 parts, where these 4 threads will run together to heap sort 5 elements (Thread 1 sorts index 0-4,Thread 2 sorts index 5-9 and so on) and finally merging them together with the merge sort technique. The merge sort works perfectly fine and so I am not including it. But the heap sort functionality fails to provide the right answer. The threads keeps revolving in the index of 14 to 19 of the array. Is there anything I am doing wrong here?
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();
}
}
Your most basic problem is that you use static
to declare fields of your thread. You should never do that.
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);
Basically your 4 threads will run only between 15-19 indexes, because you set them last.
When you fix that, please take a look at Fork/Join, it was created for specifically that:
http://www.oracle.com/technetwork/articles/java/fork-join-422606.html