作者every823 (TING)
看板java
標題[問題] Bubble Sort的問題,不知道哪裡錯了
時間Fri Nov 9 10:47:41 2018
大家好~小妹最近才剛踏入Java學習.以前完全沒寫程式經驗
如有一些很新手的問題,請鞭小力一點,感謝各位!
目前在學Bubble Sort,但寫了一段希望先用隨機數跑出來後,
再進行Bubble Sort,然後回傳進行時間,
但是在最下面排序後的下一行a卻顯示有誤
for (int
a = 0; a < aNum.length; a++)
想請各位大大解惑一下!或是該怎麼調整呢?
謝謝大家~
附上連結
https://www.codepile.net/pile/abBK9pkQ
-----------------------------------------------
public class LabBubblesort {
public static void main(String[] args) {
int[] aNum = new int[5];
for (int a = 0; a < aNum.length; a++) {
aNum[a] = (int) (Math.random() * 100);
System.out.print(" 排 序 前 :");
System.out.print(" " + aNum[a] + "\t");
System.out.println();
System.out.println(System.currentTimeMillis());
int n = aNum.length;
int t;
for (int i = n - 2; i >= 0; i--) { // 進行氣泡排序法
for (int j = 0; j <= i; j++) {
if (aNum[j] > aNum[j + 1]) {
t = aNum[j];
aNum[j] = aNum[j + 1];
aNum[j + 1] = t;
}
}
System.out.print(" 排 序 後 :");
for (int a = 0; a < aNum.length; a++)
System.out.print(" " + aNum[a] + "\t");
System.out.println();
System.out.println(System.currentTimeMillis());
}
}
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.218.5.190
※ 文章網址: https://www.ptt.cc/bbs/java/M.1541731663.A.441.html
→ starburs: 大括號 11/09 11:01
推 t52101t: 找個貼程式碼的網站來貼你的code吧 這樣看好痛苦 11/09 11:56
好的~
https://www.codepile.net/pile/abBK9pkQ
→ adrianshum: 痛苦主要不在於在哪貼,而是這段code 的indentation 11/09 12:30
→ adrianshum: 一塌胡塗... 11/09 12:30
抱歉~
※ 編輯: every823 (61.218.5.190), 11/09/2018 12:37:19
推 motherboard: a重複使用了阿... 11/09 13:54
→ fayhong: 這個檔案不能 copy,你是希望讀者重頭照你的程式key一遍? 11/09 16:07
→ fayhong: 產生資料的 for loop 怎麼沒有 close 起來再做排序呢? 11/09 16:09
→ fayhong: bubble sort 不管是從前到後還是從後到前,i 與 j 都有 11/09 16:10
→ fayhong: 1 個項次差,才能進行比較,如果按照你的方式,j = 0~i 11/09 16:11
→ fayhong: 那 i 應該是 n - 1 到 1,而不是 0 11/09 16:11
→ fayhong: 而且,j 一定不能 = i,所以 j 應該是 0 ~ (i - 1) 11/09 16:11
→ fayhong: 這樣寫 bubble sort 很難讀,建議你還是用傳統的寫法 11/09 16:12
→ fayhong: i = 0 ~ n - 2, j = i+1 ~ n-1 這樣比較好讀 11/09 16:12
→ every823: 謝謝大家~~~~^^ 11/09 21:21
推 motherboard: 原PO多去找幾篇coding style的文章看看 很有幫助的 11/09 23:41
→ every823: 好的~~謝謝 11/10 21:55