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]);
}
}
@Op並回答下一個問題:如果您打算多次調用該計數器,則需要在排序函數的開頭重置計數器。 – ABuckau
@ABuckau我認爲交換次數不應該是一個持續變量,除此之外,算法可能會關閉,我從來沒有檢查過它。 –
應該vs什麼操作實際發佈*編輯:也因爲數組通過引用傳遞,返回值是有點怪異..沒有意義,但提供了語法糖我猜 - 沒有點混淆新手。 – ABuckau