返回冒泡排序中的交换次数

时间:2016-08-02 13:01:47

标签: bubble-sort

为什么这个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]);  
 }
}

1 个答案:

答案 0 :(得分: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]);
}

我还假设你的冒泡排序的实现是正确的。在任何情况下,我的答案应该解释你得到零而不是某些价值的原因。