2017-06-04 63 views
-2

我寫了這個排序兩個數組,然後比較值,看看他們是否是相同的,但它總是返回false,我不明白爲什麼。我的代碼確定兩個數組是否是排列總是返回false,爲什麼?

它應該找出兩個數組是否是彼此的排列。

public class Permutations { 

    public static void main(String[] args) { 
     int[] a = {1,4,6,7,8,34}; 
     int[] b = {34,6,8,1,4,7}; 

     System.out.println(arePermutations(a, b)); 
    } 

    public static boolean arePermutations(int[] a, int[] b) 
    { 
     int count = 0; 
     int temp = 0; 
     if(a.length == b.length) 
     { 
      for(int i=0; i<a.length-1; i++) 
       for(int j=0; j<a.length-1; j++) 
        if(a[i] > a[j+1] && i>j+1) 
        { 
         temp = a[i]; 
         a[i] = a[j+1]; 
         a[j+1] = temp; 
        } 
      { 
       for(int i=0; i<b.length-1; i++) 
        for(int j=0; j<b.length-1; j++) 
         if(b[i] > b[j+1] && i>j+1) 
         { 
          temp = b[i]; 
          b[i] = b[j+1]; 
          b[j+1] = temp; 
         } 
      } 
      for(int i=0; i<a.length; i++) 
       if(a[i] == b[i]) 
       { 
        count++; 
       } 
      if (count == a.length) 
      { 
       return true; 
      } 
      else return false; 
     } 
     else return false; 

    } 
} 
+1

您應該將排序分爲單獨的函數並自行測試。 – Ryan

+0

請解釋一下你在這個程序中試圖做什麼的步驟。正如上面指出的那樣,用於分類和比較的單獨功能。 – denis

+0

好的,謝謝你的回答。 –

回答

1

問題是在執行氣泡排序。更改排序循環以下幾點:

for (int i = 0; i < a.length; i++) { 
     for (int j = 0; j < a.length - 1; j++) { 
      if (a[j] > a[j + 1]) { 
       temp = a[j]; 
       a[j] = a[j + 1]; 
       a[j + 1] = temp; 
      } 
     } 
    } 

    for (int i = 0; i < b.length; i++) { 
     for (int j = 0; j < b.length - 1; j++) { 
      if (b[j] > b[j + 1]) { 
       temp = b[j]; 
       b[j] = b[j + 1]; 
       b[j + 1] = temp; 
      } 
     } 
    } 

此代碼的工作,因爲冒泡排序只是交換相鄰的元素,如果他們需要交換,但需要通過整個陣列多次運行(最多的項目數數組)將所有項目放到正確的位置。

+0

您的幫助表示讚賞 –

+0

@Ski隨時接受答案 – Jason

相關問題