Chinaunix首页 | 论坛 | 博客
  • 博客访问: 19210
  • 博文数量: 4
  • 博客积分: 117
  • 博客等级: 入伍新兵
  • 技术积分: 70
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-26 21:04
文章分类
文章存档

2011年(4)

我的朋友

分类: C/C++

2011-07-07 11:40:31

  1. #include <stdio.h>

  2. void print_arry(const int *str, int length)
  3. {
  4.     int i;
  5.     
  6.     for (i = 0; i < length; i++)
  7.     {
  8.         printf("%4d", str[i]);
  9.     }
  10.     printf("\n");
  11.     
  12.     return;
  13. }

  14. void swap(int *arry, int left, int right)
  15. {
  16.     int tmpval;
  17.     
  18.     tmpval = arry[left];
  19.     arry[left] = arry[right];
  20.     arry[right] = tmpval;
  21.     
  22.     return;
  23. }

  24. int partition(int *arry, int left, int right, int pivotIndex)
  25. {
  26.     int i;
  27.     int tmpval;
  28.     int index;
  29.     
  30.     tmpval = arry[pivotIndex];
  31.     index = left;
  32.     
  33.     swap(arry, left, pivotIndex);
  34.     
  35.     for (i = left+1; i <= right; i++)
  36.     {
  37.         if (arry[i] < tmpval)
  38.         {
  39.             index++;
  40.             swap(arry, index, i);
  41.         }
  42.     }
  43.     
  44.     swap(arry, left, index);
  45.     
  46.     return index;
  47. }

  48. int select_pivotIndex(int *arry, int left ,int right)
  49. {
  50.     return (left + (right - left)/2);
  51. }

  52. void quick_sort(int *arry, int left, int right)
  53. {
  54.     int pivotIndex = 0;
  55.     int pivotNewIndex = 0;
  56.     
  57.     if (left < right)
  58.     {
  59.         pivotIndex = select_pivotIndex(arry, left, right);
  60.         pivotNewIndex = partition(arry, left, right, pivotIndex);
  61.         
  62.         quick_sort(arry, left, pivotNewIndex-1);
  63.         quick_sort(arry, pivotNewIndex+1, right);
  64.     }
  65.     
  66.     return;
  67. }


  68. int main(void)
  69. {
  70.     int length;
  71.     int arry[] = {1, 10, 30, 40 ,2, 8, 50, 70};
  72.     
  73.     length = sizeof(arry)/sizeof(arry[0]);
  74.     
  75.     print_arry(arry, length);
  76.     quick_sort(arry, 0, length-1);
  77.     print_arry(arry, length);
  78.     
  79.     return 0;
  80. }
阅读(602) | 评论(0) | 转发(0) |
0

上一篇:panic函数分析

下一篇:堆排序的实现

给主人留下些什么吧!~~