气泡排序算法有什么问题吗?

时间:2018-10-03 07:44:50

标签: java

我对编码非常陌生,在大学提交过程中运行它时,我不断收到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].

}

1 个答案:

答案 0 :(得分:0)

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

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