以从小到大排序为例(注意i, j的边界):
(1)把最大的冒泡至最右端
10
1 9 10 2 3 5 7 4 8 6
1 9 2 10 3 5 7 4 8 6
1 9 2 3 10 5 7 4 8 6
1 9 2 3 5 10 7 4 8 6
1 9 2 3 5 7 10 4 8 6
1 9 2 3 5 7 4 10 8 6
1 9 2 3 5 7 4 8 10 6
1 9 2 3 5 7 4 8 6 10
1 2 9 3 5 7 4 8 6 10
1 2 3 9 5 7 4 8 6 10
1 2 3 5 9 7 4 8 6 10
1 2 3 5 7 9 4 8 6 10
1 2 3 5 7 4 9 8 6 10
1 2 3 5 7 4 8 9 6 10
1 2 3 5 7 4 8 6 9 10
1 2 3 5 4 7 8 6 9 10
1 2 3 5 4 7 6 8 9 10
1 2 3 4 5 7 6 8 9 10
1 2 3 4 5 6 7 8 9 10
// 冒泡排序1
#include <stdio.h>
#include <algorithm>
using namespace std;
int a[1005];
int n;
void
f(int a[1005]) {
for( int i = 0; i < n; i++ ) {
printf("%d ", a[i]);
}
printf("\n");
}
int
main() {
int i, j;
while( scanf("%d", &n) != EOF ) {
for( i = 0; i < n; i++ ) {
scanf("%d", &a[i]);
}
for( i = 0; i < n - 1; i++ ) {
for( j = 0; j < n - 1 - i; j++ ) {
if( a[j] > a[j + 1] ) {
swap(a[j], a[j + 1]); // 交换次数
f(a);
}
}
}
}
return 0;
}
(2)把最小的冒泡至最左端
10
1 9 10 2 3 5 7 4 8 6
1 9 10 2 3 5 7 4 6 8
1 9 10 2 3 5 4 7 6 8
1 9 10 2 3 4 5 7 6 8
1 9 2 10 3 4 5 7 6 8
1 2 9 10 3 4 5 7 6 8
1 2 9 10 3 4 5 6 7 8
1 2 9 3 10 4 5 6 7 8
1 2 3 9 10 4 5 6 7 8
1 2 3 9 4 10 5 6 7 8
1 2 3 4 9 10 5 6 7 8
1 2 3 4 9 5 10 6 7 8
1 2 3 4 5 9 10 6 7 8
1 2 3 4 5 9 6 10 7 8
1 2 3 4 5 6 9 10 7 8
1 2 3 4 5 6 9 7 10 8
1 2 3 4 5 6 7 9 10 8
1 2 3 4 5 6 7 9 8 10
1 2 3 4 5 6 7 8 9 10
//冒泡排序2
#include <stdio.h>
#include <algorithm>
using namespace std;
int a[1005];
int n;
void
f(int a[1005]) {
for( int i = 0; i < n; i++ ) {
printf("%d ", a[i]);
}
printf("\n");
}
int
main() {
int i, j;
while( scanf("%d", &n) != EOF ) {
for( i = 0; i < n; i++ ) {
scanf("%d", &a[i]);
}
for( i = 0; i < n - 1; i++ ) {
for( j = n - 2; j >= i; j-- ) {
if( a[j] > a[j + 1] ) {
swap(a[j], a[j + 1]); // 交换次数
f(a);
}
}
}
}
return 0;
}