9.3.3
#include <stdio.h> #define MAXSIZE 10 /* 用于要排序数组个数最大值,可根据需要修改 */ typedef struct { int r[MAXSIZE+1]; /* 用于存储要排序数组,r[0]用作哨兵或临时变量 */ int length; /* 用于记录顺序表的长度 */ }SqList; /* 交换L中数组r的下标为i和j的值 */ void swap(SqList * L, int i, int j){ int temp=L->r[i]; L->r[i]=L->r[j]; L->r[j]=temp; } //打印L中数组的值 void print(SqList L){ int i; for(i=1; i<=L.length; i++) printf("%3d",L.r[i]); printf(" "); } //冒泡排序普通版 void BubbleSort1(SqList * L){ int i,j; for(i=1; i<L->length; i++){ for(j=L->length; j>i; j--){ if(L->r[j] < L->r[j-1]){ swap(L, j, j-1);//把数值大的数换到下标大的位置(从小到大排序) } } } } //冒泡排序改进版 void BubbleSort2(SqList * L){ int i,j,flag; for(i=1; i<L->length && flag; i++){ flag=0; for(j=L->length; j>i; j--){ if(L->r[j]<L->r[j-1]){ swap(L,j,j-1); flag=1; /* 如果有数据交换,则flag为1,i的下次循环还应该进行 */ } } } } int main(){ SqList L; int num[11] ={10,0,5,3,2,4,6,1,7,8,9}; for(int i=0; i<=10; i++){ L.r[i]=num[i]; }//注意给数组赋值的方法 L.length=10; BubbleSort2(&L); print(L); return 0; }
最好情况比较n-1次,最坏比较n(n-1)/2次,并做同等数量级的交换。
时间复杂度O(n^2);