【发布时间】:2016-08-02 13:01:46
【问题描述】:
为什么这个 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]);
}
}
【问题讨论】:
标签: bubble-sort