3 回答

TA貢獻1784條經驗 獲得超2個贊
您的數組已經排序,您只需將打印語句移出循環
public static void main(String [] args){
int [] a = {45,23,4,6,2};
for(int i = 0; i< a.length; i++){
for(int j = i; j>0; j--){
if(a[j]< a[j-1]){
int temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
}
}
}
// Arrays.stream(a).forEach(System.out::println); -- Java 8
for (int idx = 0; idx < a.length; idx++) {
System.out.println(a[idx]);
}
}

TA貢獻1803條經驗 獲得超6個贊
你的代碼是正確的。但是,打印元素的方式存在問題。請記住,您的數組僅在第一個 for 循環完成后a[j]
進行排序,但您是在排序過程中打印的。此時元素根本沒有排序,因此您得到錯誤的輸出。因此,您從第二個 for 循環中刪除該打印語句,并在排序結束后使用另一個 for 循環進行打印。
添加回答
舉報