2016-08-31 85 views
1

所以簡單地說,我正在開發一個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

您最基本的問題是您使用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個索引之間運行,因爲你將它們設置爲最後一個。

當你解決這個問題,請看看叉/加入,它是專門創建:

http://www.oracle.com/technetwork/articles/java/fork-join-422606.html