【问题标题】:Why in bubble sort I get number of swaps (instead of Zero) when I try to enter a sorted array?为什么在冒泡排序中,当我尝试输入排序数组时,我得到交换次数(而不是零)?
【发布时间】:2017-10-30 19:30:41
【问题描述】:

> Bubble `BUUBLE

> Sorting
**SWAPING**

`
       import java.util.Random;

        public class bubble {
**Initializing**
  public static int count1 = 0;
  public static int swap = 0;

  public static int[][] Bubbles(int[] a) {
    int output[] = new int[2];
    for (int pass = 0; pass < a.length; pass++) {
      for (int i = 0; i < a.length - 1; i++) {
        count1++;
        if (a[i] > a[i + 1]) {
          int temp = a[i];
          a[i] = a[i + 1];
          a[i + 1] = temp;
          swap++; 

        }
      }
    }
    output[0] = swap;
    output[1] = count1;

    return new int[][] {
      a,
      output
    };
  }
}


Bubble sort **Bubble**

【问题讨论】:

  • 我在一个有序数组上运行了你的代码,得到了swap = 0...

标签: java bubble-sort


【解决方案1】:

这取决于您的输入数组是按升序还是降序排序。如果您的输入数组的顺序如下:{10, 9, 8, ...} then a[0] > a[1],您将在嵌套 for 循环中输入 if-then 构造,递增交换。因此,您将获得一个非零的交换值。

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-05
    • 1970-01-01
    • 2019-12-29
    • 2015-09-12
    • 2015-04-10
    相关资源
    最近更新 更多