常用排序算法之——快速排序(C語言+VC6.0平台)


經典排序算法中快速排序具有較好的效率,但其實現思路相對較難理解。

#include<stdio.h>

 int partition(int num[],int low,int high) //以key為基准 將待排數列“高”、“低 ”兩部分,“高”部分的所有數據比key大,“低”部分的數據都比key小

{

         int left,right,key;

         left=low;right=high;key=num[low];

         while(left<right)

         {

                  while(left<right && num[right]>=key)

                          right--;

                  num[left]=num[right];

                   while(left<right && num[left]<=key)

                          left++;

                  num[right]=num[left];

         }

         num[left]=key;

         return left;

}

 void quick_sort(int num[],int low,int high)//遞歸實現快速排序

{

         if(low<high)

         {

                  int pos=partition(num,low,high);

                  quick_sort(num,low,pos-1);

                  quick_sort(num,pos+1,high);

         }

}

int main()

{

         int data[10]={32,33,21,14,36,7,6,4,2,11};

         int i;

         for(i=0;i<10;i++)

                  printf("%d ",data[i]);

         printf("\n");

          quick_sort(data,0,9);

          for(i=0;i<10;i++)

                  printf("%d ",data[i]);

         printf("\n");

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM