/*exp11-4*/
#include <stdio.h>
#define MAXE 20/*線性表中最多元素個數*/
typedef int KeyType;
typedef char InfoType[10];
typedef struct /*記錄類型*/
{
KeyType key;/*關鍵字項*/
InfoType data;/*其他資料項目,類型為InfoType*/
}RecType;
void QuickSort(RecType R[],int s,int t)/*對R[s]至R[t]的元素進行快速排序*/
{
int i=s,j=t,k;
RecType temp;
if(s<t)/*區間內至少存在一個元素的情況*/
{
temp=R[s];/*用區間的第1個記錄作為基準*/
while(i!=j)/*從區間兩端交替向中間掃描,直至i=j為止*/
{
while(j>i && R[j].key>temp.key)
j--;/*從右向左掃描,找第1個關鍵字小於temp.key的R[j]*/
if(i<j)/*表示找到這樣的R[j],R[i]與R[j]交換*/
{
R[i]=R[j];
i++;
}
while(i<j && R[i].key<temp.key)
i++;/*從左向右掃描,找第1個關鍵字大於temp.key的R[i]*/
if(i<j)/*表示找到這樣的R[i],R[i]與R[j]交換*/
{
R[j]=R[i];
j--;
}
}
R[i]=temp;
printf(" ");
for(k=0;k<10;k++)
if(k==i)
printf(" [%d]",R[k].key);
else
printf("%4d",R[k].key);
printf("\n");
QuickSort(R,s,i-1);/*對左區間遞迴排序*/
QuickSort(R,i+1,t);/*對右區間遞迴排序*/
}
}
void main()
{
int i,k,n=10;
KeyType a[]={6,8,7,9,0,1,3,2,4,5};
RecType R[MAXE];
for(i=0;i<n;i++)
R[i].key=a[i];
printf("\n");
printf(" 初始關鍵字");
for(k=0;k<n;k++)/*輸出初始關鍵字序列*/
printf("%4d",R[k].key);
printf("\n");
QuickSort(R,0,n-1);
printf(" 最後結果 ");
for(k=0;k<n;k++)/*輸出最後關鍵字序列*/
printf("%4d",R[k].key);
printf("\n\n");
}