2016-08-02 16 views
1
爲什麼這個getNumSwaps()方法不返回實例的值可變 numberOfSwaps

在主函數調用該方法,但其不結果要返回在氣泡互換的數目排序

public class Solution { 
public int numberOfSwaps; 
Solution(){} 
    public int[] bubbleSort(int[] x){ // To sort the array 
    for (int i = 0; i < x.length; i++) { 
     for (int j = 0; j < x.length - 1; j++) { 
      if (x[j] > x[j + 1]) { 
       int tmp = x[j]; 
       x[j] = x[j + 1]; 
       x[j + 1] = tmp; 
       this.numberOfSwaps++;//This counts the number of Swaps 
      } 
     } 
     if (numberOfSwaps == 0) { 
     break; 
     } 
    } 
    return x; 
} 
public int getNumOfSwaps(){ //this method returns zero. ?? 
    return this.numberOfSwaps; 
} 

public static void main(String[] args) { 
     Scanner sc=new Scanner(System.in); 
     int arrLength=sc.nextInt();int i=0; 
      int [] myArry=new int[arrLength]; 
      Solution sln=new Solution(); 
      while(i<arrLength){ 
      myArry[i]=sc.nextInt(); 
      i++; 
     } 
     System.out.println("Array is sorted in "+sln.getNumOfSwaps()+" swaps."); 
     System.out.println("First Element: "+sln.bubbleSort(myArry)[0]+ 
         "\nLast Element: "+sln.bubbleSort(myArry)[arrLength-1]); 
} 
} 

回答

3

你打電話給getNumOfSwaps()之前你實際上排序數組,因此你得到的默認值爲零。你main()方法應該是這個樣子:

public static void main(String[] args) { 
    Scanner sc = new Scanner(System.in); 
    int arrLength = sc.nextInt(); 
    int i = 0; 
    int[] myArry = new int[arrLength]; 
    Solution sln = new Solution(); 
    while (i < arrLength) { 
     myArry[i] = sc.nextInt(); 
     i++; 
    } 

    // first sort the array, populating the number of swaps counter 
    int[] myArrySorted = sln.bubbleSort(myArry); 

    // then access the number of swaps counter 
    System.out.println("Array is sorted in " + sln.getNumOfSwaps() + " swaps."); 
    System.out.println("First Element: " + myArrySorted[0] + 
         "\nLast Element: " + myArrySorted[arrLength-1]); 
} 

我也假設你的泡沫執行排序是正確的。無論如何,我的答案應該解釋你得到零的原因,而不是一些價值。

+1

@Op並回答下一個問題:如果您打算多次調用該計數器,則需要在排序函數的開頭重置計數器。 – ABuckau

+0

@ABuckau我認爲交換次數不應該是一個持續變量,除此之外,算法可能會關閉,我從來沒有檢查過它。 –

+0

應該vs什麼操作實際發佈*編輯:也因爲數組通過引用傳遞,返回值是有點怪異..沒有意義,但提供了語法糖我猜 - 沒有點混淆新手。 – ABuckau