清华大学出版社 TSINGHUA UNIVERSITY PRESS 例63:输入10个数,用起泡法对这10个数排序(由小到大 8 第一趟比较 4 5-420 859420 854209 0 第1次第2次第3次第4次第5次结果 经过第一趟(共5次比较与交换)后,最大的数9已“沉 底”。然后进行对余下的前面5个数第二趟比较
例6.3:输入10个数,用起泡法对这10个数排序(由小到大 )。 第 一 趟 比 较 经过第一趟(共5次比较与交换)后,最大的数9已“沉 底” 。然后进行对余下的前面5个数第二趟比较
清华大学出版社 TSINGHUA UNIVERSITY PRESS 8 5420 8420 542 542 第二趟比较 第1次第2次第3次第4次结果 如果有n个数,则要进行n-1趟比较。在第1趟比较 中要进行n-次两两比较,在第趟比较中要进行 nj次两两比较
第 二 趟 比 较 如果有n个数,则要进行n-1趟比较。在第1趟比较 中要进行n-1次两两比较,在第j趟比较中要进行 n-j次两两比较
清华大学出版社 TSINGHUA UNIVERSITY PRESS 程序流程图如下: 输入n个数给a[1到a[n] for j=1 to n-1 or 1 to n-J ali>ali+ 真 假 a[i今a[i+1 输出a[1]到a[n]
程序流程图如下:
清华大学出版社 TSINGHUA UNIVERSITY PRESS 程序实例63 #include <stdio.h> void maino int a [10] Int 13, t printf("input 10 numbers: n") for(i=0;i<10i+) scanf(%od",&aiD) printf("n");
程序实例6.3: #include <stdio.h> void main() { int a[10]; int i,j,t; printf(″input 10 numbers :\n″); for (i=0;i<10;i++) scanf("%d",&a[i]); printf("\n");
清华大学出版社 TSINGHUA UNIVERSITY PRESS for(=0<9j++) for(i=0;i<9-j;i++) if (a [i] >a [i+1]) t=all; ai=ai+ll a[i+1] 程序运行结果如下: printf( "the sorte input 10 numbers for(=010计10481265-76100-45123∠ printf("%od printf("n"), the sorted numbers }/伴程序结束*/-76-4501481265100123
for(j=0;j<9;j++) for(i=0;i<9-j;i++) if (a[i]>a[i+1]) { t=a[i];a[i]=a[i+1]; a[i+1]=t; } printf(″the sorted numbers :\n″); for(i=0;i<10;i++) printf(″%d ″,a[i]); printf(″\n″); }/*程序结束*/ 程序运行结果如下: input 10 numbers: 1 0 4 8 12 65 -76 100 -45 123↙ the sorted numbers: -76 -45 0 1 4 8 12 65 100 123