2015-09-14 35 views
0

該算法在課堂上給我們:ComparisonCountingSort僞難度

enter image description here

我有我試圖確定輸出當輸入是一個數組 A[60,35,81,98,14,47]麻煩

我想習慣僞代碼語法,所以我試圖將其轉換爲Java語法,但是生成的程序不會顯示結果。這是我的轉換代碼:

public class Driver 
{ 
    public static void main(String[] args) 
    { 
     int[] test = {60, 35, 81, 98, 14, 47}; 
     int[] converse = new int[6]; 

     converse = countSort(test); 

     for(int i : converse) 
     { 
      System.out.println(converse[i]); 
     } 
    } 

    public static int[] countSort(int[] a) 
    { 
     int[] s = new int[6]; 
     int[] count = new int[6]; 
     int n = a.length + 1; 

     for(int i = 0; i < (n-1);) 
     { 
      count[i] = 0; 
     } 

     for(int i = 0; i < (n-2);) 
     { 
      for(int j = (i+1); i < (n-1);) 
      { 
       if(a[i] < a[j]) 
       { 
        count[j] = count[j]+1;//What 
       } 
       else 
       { 
        count[i] = count[i]+1; 
       } 
      } 
     } 

     for (int i = 0; i < (n-1);) 
     { 
      s[count[i]] = a[i]; 
     } 

     return s; 
    } 
} 

回答

3

int[] test = {60,35,81,98,14,47};從不使用。

您是不是要將test轉換成countSort?並對結果做一些事情。

雖然我還沒有在算法看起來真的,還有別的東西錯在這裏:

int n = a.length + 1; for (int i = 0; i < (n - 1);) { count[i] = 0; }

這將循環indefinatetly。 i絕不會增生。

+0

哎呀離開了,我有它,但我必須刪除它。同樣的問題。 –

+0

實際上,在所有四個循環中都會出現增加循環控制變量的同樣故障。這是將僞代碼正確轉換爲Java的失敗。 –

+0

感謝關鍵錯誤 –

1
  1. 從未使用您的陣列test
  2. 在您的for循環中,i永遠不會遞增。它會循環無限。
  3. 而不是n = a.length+1;只是使用n = a.length。它使您的代碼更易於閱讀。然後你也必須檢查你所有的循環。

當正在運行與測試集更大或小於6整數值的代碼不會正確地運行,甚至失敗,並ArrayOutOfBounds例外,因爲你分配陣列scount僅6個值的代碼。 嘗試int[] count = new int[a.length];而不是int[] count = new int[a.length];s也一樣。