Chinaunix首页 | 论坛 | 博客
  • 博客访问: 120575
  • 博文数量: 31
  • 博客积分: 691
  • 博客等级: 中士
  • 技术积分: 245
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-16 16:45
文章分类

全部博文(31)

文章存档

2012年(4)

2011年(27)

分类: LINUX

2012-10-14 11:15:41

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

点击(此处)折叠或打开

  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. }

阅读(3078) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~