首页 > 解决方案 > 这个冒泡排序算法有什么问题吗?

问题描述

我对编码很陌生,当我在大学提交过程中运行它时,我不断收到 ArrayOutofBoundsError: 8 。我不明白为什么。错误也指向交换方法,但是我什至没有写这个,因为它是骨架的一部分。仅当我尝试使用自己的冒泡排序方法时才会出现此问题。所以我认为它一定有问题。所有其他方法单独工作正常。

  public void sortBubble()
{
   /* This implementation uses the bubble sort algorithm. For an explanation
    * of how bubblesort works, google ...
    *            bubblesort java
    */

   // with variable subscripts ...
   int i = 0; // role: stepper

   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
   ++i;
   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
   ++i;
   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);


   // At this point, the largest element must be in list[3].

   i = 0;
   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);
   ++i;
   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);

   // At this point, the second largest element must be in list[2].

   i=0;
   if ( list[i] > list[i+1] ) swap(list[i], list[i+1]);

   // At this point, the smallest element must be in list[0].

}

标签: java

解决方案


为什么不使用循环?这就足够了。

for (int i = 0; i < ( n - 1 ); i++) {
  for (int j = 0; j < n - i - 1; j++) {
    if (array[j] < array[j+1]) /* For ascending order use > */
    {
      int swap       = array[j];
      array[j]   = array[j+1];
      array[j+1] = swap;
    }
  }
}

示例代码:

import java.util.Scanner;

class Demo {
  public static void main(String []args) {
    int n = 3; // Number of elements
    Scanner in = new Scanner(System.in);

    int array[] = new int[n];

    System.out.println("Enter " + n + " integers");

    for (int i = 0; i < n; i++)
      array[i] = in.nextInt();

    // Sorting in descending order
    for (int i = 0; i < ( n - 1 ); i++) {
      for (int j = 0; j < n - i - 1; j++) {
        if (array[j] < array[j+1]) /* For ascending order use ">" */
        {
          int swap       = array[j];
          array[j]   = array[j+1];
          array[j+1] = swap;
        }
      }
    }

    // Display the sorted list
    System.out.println("Sorted list of numbers:");

    for (int i = 0; i < n; i++)
      System.out.println(array[i]);
  }
}

推荐阅读