尾递归优化快速排序

3115阅读 0评论2012-10-14 lys5300
分类:LINUX

 尾递归与递归效率差不多,但是可以减少递归深度。

点击(此处)折叠或打开

  1. #include<stdio.h>


  2. /*
  3.  * 关于使用尾递归优化快速排序算法*/


  4. /* 划分函数*/
  5. int
  6. Partition(int *list,int low , int high){
  7.     int pivot;

  8.     pivot = *(list + low);
  9.     while (low < high)
  10.     {
  11.         while (low < high && *(list + high) >= pivot)
  12.             high--;
  13.         *(list+low) = *(list+high);
  14.         while (low < high && *(list + low) < pivot)
  15.             low++;
  16.         *(list+high) = *(list+low);
  17.     }
  18.     *(list+low) = pivot;
  19.     return low;
  20. }

  21. /* quick sort*/
  22. void
  23. quicksort(int *list,int low,int high){
  24.     int pivot;

  25.     while (low < high){
  26.         pivot = Partition(list,low,high);
  27.         if (pivot - low < high - pivot)
  28.         {
  29.             quicksort(list,low,pivot - 1);
  30.             low = pivot + 1;
  31.         }
  32.         else
  33.         {
  34.             quicksort(list,pivot + 1,high);
  35.             high = pivot - 1;
  36.         }
  37.         //quicksort(list,pivot+1,high);
  38.         //quicksort(list,low,pivot-1);
  39.     }
  40. }

  41. int
  42. main(int argc,char* argv[])
  43. {
  44.     int list[] = {5,2,45,12,32,34,4,7,23,2};
  45.     int i;
  46.     for (i = 0;i < 10;i++)
  47.         printf("%d ",list[i]);
  48.     putchar('\n');

  49.     quicksort(list,0,9);

  50.     for (i = 0;i < 10;i++)
  51.         printf("%d ",list[i]);
  52.     putchar('\n');
  53.     return 0;
  54. }

上一篇:关于用python重构terminal下的词典
下一篇:关于合并两个有序数组