快排中partition函数的几种写法记录

 

 
  1. void swap(int *a, int *b) {

  2.     if(a == b) return ;

  3.     int temp = *a; 

  4.     *a = *b; 

  5.     *b = temp;

  6.     return ;

  7. }

  8. int partition1(int *a, unsigned low, unsigned high) {

  9.     if(low >= high) return 0;

  10.     int i = 0;

  11.     int pVotPos = low; //pVotPos指向根据pVotVal大小分割处的小

  12.     int pVotVal = a[low];

  13.     for(i=low+1;i<=high;i++) {

  14.         if(a[i]<pVotVal) {

  15.             pVotPos++;

  16.             swap(a+pVotPos, a+i);

  17.         }   

  18.     }   

  19.     swap(a+low, a+pVotPos); //把小的换到前面

  20.     return pVotPos;

  21. }

  22. int partition2(int *a, unsigned low, unsigned high) {

  23.     if(low >= high) return 0;

  24.     int i = 0;

  25.     int pVotPos = low+1; //pVotPos指向根据pVotVal大小分割处的大

  26.     int pVotVal = a[low];

  27.     for(i=low+1;i<=high;i++) {

  28.         if(a[i]<pVotVal) {

  29.             swap(a+pVotPos, a+i);

  30.             pVotPos++;

  31.         }   

  32.     }   

  33.     swap(a+low, a+pVotPos-1); //大的左边一个位置上存的即为小,把小的换到前面

  34.     return pVotPos-1;

  35. }

  36.  
  37.  
  38. int partition3(int *a, unsigned low, unsigned high) {                                                                                                                                                      

  39.     if(low >= high) return 0;

  40.     int i = low, j = high;

  41.     int pVotVal = a[low]; //把pVotPos的值存起来,并形成一个可用的槽

  42.     while(i<j) {

  43.         while(a[j]>pVotVal && j>i) j--; //从末端找小的

  44.         a[i]=a[j]; //换到前面去

  45.         while(a[i]<pVotVal && i<j) i++; //从前端找大的

  46.         a[j]=a[i]; //换到后面去

  47.     }   

  48.     a[j]=pVotVal;

  49.     return j;

  50. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值