导航

快速排序

Posted on 2014-08-19 15:48  smallstrong  阅读(154)  评论(0编辑  收藏  举报
  1. #include <cstdio>  
  2. #define ARRLEN(x) (sizeof(x)/sizeof(int))  
  3. int partition(int a[], int low, int high)  
  4. {  
  5.     int pivotkey=a[low];  
  6.     while (low<high)  
  7.     {  
  8.         while (low<high && a[high]>=pivotkey)  
  9.             --high;  
  10.         if (low<high)   
  11.             a[low++]=a[high];  
  12.         while (low<high && a[low]<=pivotkey)  
  13.             ++low;  
  14.         if (low<high)   
  15.             a[high--]=a[low];  
  16.     }  
  17.     a[low]=pivotkey;  
  18.     return low;  
  19. }  
  20. void quicksort(int a[], int low, int high)  
  21. {  
  22.     int pivotpos;  
  23.     if (low<high)  
  24.     {  
  25.         pivotpos=partition(a,low,high);  
  26.         quicksort(a,low,pivotpos-1);  
  27.         quicksort(a,pivotpos+1,high);  
  28.     }  
  29. }  
  30. int main()  
  31. {  
  32.     int a[]={2,7,9,3,1,4,8,0,6,2};  
  33.     int i;  
  34.     for (i=0; i<ARRLEN(a); printf("%2d",a[i]),++i);  
  35.     printf("/n");  
  36.     quicksort(a,0,ARRLEN(a)-1);  
  37.     for (i=0; i<ARRLEN(a); printf("%2d",a[i]),++i);  
  38.     printf("/n");  
  39.     return 0;  
  40. }