冒泡排序算法(小——>大)描述:
实质——小的数向上冒,大的数向下沉
示例:对数组进行从大到小的冒泡法排序
对于数组{7,8,9,6,5,4,3,2,1,0}的array[10]
第一次遍历:从数组的第一个索引值开始,与其向下相邻的数进行比较——7与8进行比较,7<8
不进行位置交换,将比较索引值+1,即比较值的索引上的数组值为8,向下相邻值比较——8与9进行比较,8<9,不进行值的交换
将比较索引值+1,即比较值的索引上的数组值为9,向下相邻值比较——8与9进行比较,9>6,进行值的交换
······
直到索引值与数组的索引值的最大值相等,则第一次遍历结束
第二次遍历
······
遍历n-1次
······
#include "stdio.h"
#define SIZE 10int main( void )
{
int a[SIZE] = {9,8,7,6,5,4,3,2,1,0};//实例化数组a[SIZE]
int pass;//遍历次数
int i;//用来交换数值的索引
int hold;//用来进行交换的数值参数
//打印最开始的数组值
printf( "Data items in origional order\n" );
for( i = 0; i < SIZE; i++ ) {
printf( "%4d", a[i] );
}
//遍历
for( pass = 1; pass < SIZE; pass++ ) {
//冒泡排序
for( i = 0; i < SIZE-1; i++ ) {
if( a[i] > a[i+1] ) {
hold = a[i];
a[i] = a[i+1];
a[i+1] = hold;
}
}
}
//打印经过冒泡排序之后的数组值
printf( "\nData items in assending order\n" );
for( i = 0; i <SIZE; i++ ) {
printf( "%4d", a[i] );
}
printf( "\n" );
return 0;
}