2016-04-28 58 views
0

我必須編寫一個氣泡排序程序,並將它編碼出來,但出於某種原因,我的輸出完全是瘋了。這是一些輸出...列表一直到190重複同樣的事情; 「[I @ 5b787144」使用隨機生成的數組進行氣泡排序

49, 21, 45, 22, 28, 55, 91, 34, 69, 27, 40, 60, 41, 14, 45, 79, 93, 11, 89, 77, 1)[[email protected] 
2)[[email protected] 
3)[[email protected] 

這是我的代碼。

import java.util.Random; 

public class Bubble 
{ 
    public void generate() 
    { 
     int k; 
     int a[]; 
     int count = 1; 
     a = new int[20]; 
     for (int i = 0; i < 20; i++) 
     { 
      Random rand = new Random(); 
      a[i] = rand.nextInt(100); 
      System.out.print(a[i] +", "); 
     } 
     for (int h = 0; h < a.length-1; h++) 
     { 
      for (int j = 1; j < a.length-h; j++) 
       { 
        if (a[j-1] > a[j]) 
        { 
         k = a[j-1]; 
         a[j-1] = a[j]; 
         a[j] = k; 
        } 

        System.out.println(+count+ ")" +a); 
        count++; 
       } 
     } 
    } 
} 

我需要它按升序排序它,同時打印出的那種每次迭代。

+0

退房[Arrays.toString() ](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(INT [])) – BevynQ

回答

0

您打印一個,它是一個對象。它試圖打印該對象的內存地址。你想打印數組中的所有元素。我建議你寫一個輔助方法,因爲你做多地方:

private void printArr(int[] array) { 
for (int i : array) { 
    System.out.print(i + ""); 
} 
System.out.println(); 
} 

然後,而不是調用

System.out.println(+count+ ")" +a); 

System.out.print(count + ""); 
printArr(a);