實現快速排序演算法

來源:互聯網
上載者:User

/*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");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.