【问题标题】:To return number of swaps in the bubble sort返回冒泡排序中的交换次数
【发布时间】: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


    【解决方案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]);
    }
    

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

    【讨论】:

    • @Op 并回答下一个问题:如果您打算多次调用排序函数,则需要在开始时重置计数器。
    • @ABuckau 我不认为交换的数量首先应该是一个持久变量,除此之外,算法可能会关闭,我自己从未检查过。
    • 应该与 Op 实际发布的内容相比 * 编辑:另外,由于数组是通过引用传递的,因此返回值有点奇怪.. 毫无意义,但我猜确实提供了语法糖 - 让新手感到困惑没有意义.
    • @TimBiegeleisen 是的得到了结果。
    猜你喜欢
    • 1970-01-01
    • 2012-07-05
    • 2016-04-04
    • 2012-07-05
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    相关资源
    最近更新 更多