起泡法的思路是:將相鄰的兩個數比較,將小的調到前頭。
可以推知,如果有 n 個數,則要進行 (n-1) 輪比較和交換。在第一輪要進行 (n-1) 次兩兩比較,在 j 輪中要進行 (n-j) 次兩兩比較。
下面將10個數從小到大進行排序:
#include<iostream>
using namespace std;
int main() {
int a[11];
int i, j, t;
cout<<"input 10 numbers:\n";
for (i=1; i<11; i++) {
cin>>a[i];
}
cout<<endl;
for (j=1; j<=9; j++) {
for(i=1; i<=10-j; i++) {
if (a[i] > a[i+1]) {
t = a[i];
a[i] = a[i+1];
a[i+1] = t;
}
}
}
cout<<"the sorted numbers: \n";
for (i=1; i<11; i++) {
cout<<a[i]<<endl;
}
cout<<endl;
return 0;
}