To return 冒泡排序中的交换次数

To return number of swaps in the bubble sort

为什么这个 getNumSwaps() 方法不 return 实例变量的值 numberOfSwaps

在main函数中调用方法无果

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]);  
 }
}

您在 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]);
}

我还假设您对冒泡排序的实施是正确的。无论如何,我的回答应该解释你得到零而不是某个值的原因。