2015-10-14 146 views
-4

我尝试使用冒泡排序来对数组进行排序,但是在每次迭代之后最后一个索引缺失。编译后输出错误

以下是我的Java代码,请帮助。

package arraytest; 

public class BubbleSort { 

    public static void main(String[] args) { 
     int [] bblSort = {30, 45, 8, 204, 165, 95, 28, 180, 110, 40}; 

     for(int i=0; i<bblSort.length; i++){ 
      System.out.print(" " +bblSort[i]); 
     } 
     System.out.println(); 
     System.out.println("  .........."); 

     sort(bblSort); 
    } 

    public static void sort(int [] bblSort){ 

     int temp=0; 
     for(int i=0; i<bblSort.length-1; i++){ 
      for(int j=0; j<bblSort.length-1 -i; j++){ 

       if(bblSort[j] > bblSort[j+1]){ 
        temp = bblSort[j]; 
        bblSort[j] = bblSort[j + 1]; 
        bblSort[j+1] = temp; 
       } 
       System.out.print(" " +bblSort[j]); 
      } 
      System.out.println(); 

     } 
    } 
} 

的程序编译

30 45 8 204 165 95 28 180 110 40 
     .......... 
30 8 45 165 95 28 180 110 40 
8 30 45 95 28 165 110 40 
8 30 45 28 95 110 40 
8 30 28 45 95 40 
8 28 30 45 40 
8 28 30 40 
8 28 30 
8 28 
8 
+1

您在使用调试器时发现了什么? –

+0

您的预期产出是什么 –

+0

请仔细检查您实际打印的内容。 –

回答

1

后的输出有什么不对您的实现。在对它进行排序后,再次输入bblSort的内容,您将看到它看起来像这样:

[8, 28, 30, 40, 45, 95, 110, 165, 180, 204]