當我輸入1,2,3,4,5作爲輸入。輸出很好,因爲它已經從最低到最高排序。但是,當我鍵入5,4,3,2,1它的輸出:冒泡排序:爲什麼它不能正常工作?
4,3,2,1,5
我想要的方式做冒泡排序。
main() {
int a[5], i, smallest, temp;
cout << "Enter 5 numbers: " << endl;
for (i = 0; i <= 4; i++) {
cin >> a[i];
}
for (i = 0; i <= 4; i++) {
smallest = a[i];
if (smallest > a[i+1]) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
}
cout << endl << endl;
for (i = 0; i <= 4; i++) {
cout << a[i] << endl;
}
system("pause");
}
我沒有改變我的代碼,這是你有幫助的答覆後:
for (i = 0; i <=4; i++) {
smallest = a[i];
for (j = 1; j <= 4; j++) {
if (smallest > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
我不知道爲什麼它不工作。我真的很抱歉,因爲我是編程小白菜,所以請耐心等待我剛剛開始:)
任何幫助將不勝感激。 。
謝謝^^
這聽起來像你可能需要學習如何使用調試器來遍歷你的代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
,因爲您只完成一次迭代 –
請比較您的算法[Wikipedia上的定義](https://en.wikipedia.org/wiki/Bubble_sort)。你錯過了一個循環。 – starturtle