程序运行截图如下:
程序代码如下:
1 #include2 #include 3 #include 4 #define MAXSIZE 20 5 typedef int KeyType; 6 typedef char InfoType; 7 8 //结构体定义 9 typedef struct {10 KeyType key;11 InfoType otherinfo;12 }RedType;13 typedef struct {14 RedType r[MAXSIZE+1];15 int length;16 }SqList;17 18 //各个函数定义19 void print(SqList *L);20 void init(SqList *L);21 void BubbleSort(SqList *L);22 23 //初始化,随机产生待排序的数组24 void init(SqList *L) {25 int n,i;26 printf("请输入待排序的元素个数:");27 scanf("%d",&n);28 srand(((int)time(0)));//设置随机种子29 for(i=1; i<=n; i++) {30 L->r[i].key = rand()%10+1;31 }32 L->length = n;33 printf("随机产生的待排数组为:");34 print(L);35 printf("\n");36 }37 38 //输出数组元素39 void print(SqList *L) {40 int i;41 for(i=1; i<=L->length; i++) {42 printf("%d ",L->r[i].key);43 }44 printf("\n");45 }46 47 //进行冒泡排序48 void BubbleSort(SqList *L) {49 int i,j,t;50 for(i=1; i<=L->length;i++) {51 for(j=i+1; j<=L->length; j++) {52 if(L->r[j].key < L->r[i].key) {53 L->r[0] = L->r[j];54 L->r[j] = L->r[i];55 L->r[i] = L->r[0];56 }57 }58 printf("第%d次排序的结果为:",i);59 print(L);60 }61 printf("\n");62 }63 64 //主函数65 int main()66 {67 SqList sq;68 init(&sq);69 BubbleSort(&sq);70 printf("排序之后的数组为:");71 print(&sq);72 return 0;73 }