冒泡排序算法改進版:
#include <stdio.h>
#define MaxSize 20
typedef int KeyType; //定義關鍵字類型
typedef char InfoType[10];
typedef struct //記錄類型
{
KeyType key; //關鍵字項
InfoType data; //其他數據項,類型爲InfoType
} RecType; //排序的記錄類型定義
void BubbleSort1(RecType R[],int n)
{
int i,j,k,exchange;
RecType tmp;
for (i=0;i<n-1;i++)
{
exchange=0;
for (j=n-1;j>i;j--) //比較,找出最小關鍵字的記錄
if (R[j].key<R[j-1].key)
{
tmp=R[j]; //R[j]與R[j-1]進行交換,將最小關鍵字記錄前移
R[j]=R[j-1];
R[j-1]=tmp;
exchange=1;
}
printf("i=%d: ",i);
for (k=0;k<n;k++)
printf("%d ",R[k].key);
printf("\n");
if (exchange==0) //中途結束算法
return;
}
}
void main()
{
int i,n=10;
RecType R[MaxSize];
KeyType a[]={0,1,7,2,5,4,3,6,8,9};
for (i=0;i<n;i++)
R[i].key=a[i];
printf("排序前:");
for (i=0;i<n;i++)
printf("%d ",R[i].key);
printf("\n");
BubbleSort1(R,n);
printf("排序後:");
for (i=0;i<n;i++)
printf("%d ",R[i].key);
printf("\n");
}