快速排序

快速排序算法里的partition函数用来解决这样一个问题:给定一个数组arr[]和数组中任意一个元素a,重排数组使得a左边都小于它,右// arr[]为数组,start、end分别为数组第一个元素和最后一个元素的索引
 // povitIndex为数组中任意选中的数的索引
int partition(int arr[], int start, int end, int pivotIndex)
{
    int pivot = arr[pivotIndex];
    swap(arr[pivotIndex], arr[end]);
    int storeIndex = start;
    //这个循环比一般的写法简洁高效,呵呵维基百科上看到的
    for(int i = start; i < end; ++i) {
        if(arr[i] < pivot) {
            swap(arr[i], arr[storeIndex]);
            ++storeIndex;
        }
    }
    swap(arr[storeIndex], arr[end]);
    return storeIndex;

}不小于它。


另外, 上面的partition虽然简洁, 但是并不高效, 交换次数较多.
例如: 8 1 3 9 2 4 1 9 8 7 [5], 以5为pivot按照上面的partition需要5+1次swap, 而下面的代码只需要2+1次


static  int  partition( int  A[],  int  start,  int  end,  int  pivotIndex){
     int  i = start, j = end, pivot = A[pivotIndex];
     swap< int >(A[end], A[pivotIndex]);
     while (i < j){
         while (i < j && A[i] <= pivot) ++i;
         while (i < j && A[j] >= pivot) --j;
         if (i < j) swap< int >(A[i], A[j]);
     }
     swap< int >(A[end], A[i]);
     return  i;
}
http://blog.csdn.net/kevin_luan/article/details/37737553

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值