Chinaunix首页 | 论坛 | 博客
  • 博客访问: 49886
  • 博文数量: 27
  • 博客积分: 716
  • 博客等级: 上士
  • 技术积分: 285
  • 用 户 组: 普通用户
  • 注册时间: 2011-08-31 11:12
文章分类

全部博文(27)

文章存档

2012年(8)

2011年(19)

我的朋友

分类: C/C++

2011-10-06 11:10:29

  1. #include <stdio.h>

  2. static unsigned pcount;
  3. static unsigned qcount;

  4. int partition(int array[], int p, int r)
  5. {
  6.     int key;
  7.     int i,j;
  8.     pcount++;

  9.     key = array[r];
  10.     i = p-1;

  11.     for(j = p; j < r; j++) {
  12.         if(array[j] < key) {
  13.             i++;
  14.             if(array[i] != array[j]) {
  15.                 array[i] ^= array[j];
  16.                 array[j] ^= array[i];
  17.                 array[i] ^= array[j];
  18.             }
  19.         }
  20.     }

  21.     if(array[i+1] != array[j]) {
  22.         array[i+1] ^= array[j];
  23.         array[j] ^= array[i+1];
  24.         array[i+1] ^= array[j];
  25.     }

  26.     return i+1;
  27. }

  28. void quick_sort(int array[], int p, int r)
  29. {
  30.     int q,i;
  31.     qcount++;

  32.     if(p < r) {
  33.         q = partition(array,p,r);
  34.         quick_sort(array,p,q-1);
  35.         quick_sort(array,q+1,r);
  36.     }
  37. }

  38. int main()
  39. {
  40.     int array[5] = {9,8,6,7,5};
  41.     int i;

  42.     for(i=0; i < 5; i++) {
  43.         printf("%2d",array[i]);
  44.     }
  45.     printf("\n");

  46.     quick_sort(array,0,4);

  47.     for(i=0; i < 5; i++) {
  48.         printf("%2d",array[i]);
  49.     }
  50.     printf("\n");
  51.     printf("pcount=%d,qcount=%d\n",pcount,qcount);
  52. }
复杂度:T(N)=2*T(N/2)+cN, T(N)=O(N*lgN)
阅读(612) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~