partition实现

In Quicksort algorithm implementation, the partition method is the key to make average performance as O(nlgn). As written in different algorithm textbook, it has different implementations, in many domestic data structure textbook, the 2 pointers move towards each other, accoring to this implementation, it is very hard to deal with duplicated element condition. However, in Leiserson's Introduction to Algorithm, the 2 pointers move in same direction, its performance is really enhanced and the duplicated elements can be handled gracefully as well。


Method 1: choose the last element in array as pivot,the swap loop starts from the first element of array


template<class T>
int partition1(T A[], int p, int q) {
    T pivot = A[q];
    int i = p-1;
   
    for (int j = p; j < q; j++) {
        if (A[j] <= pivot) {
            i++;
            std::swap(A[i], A[j]);
        }
    }
    std::swap(A[i+1], A[q]);
    return i+1;
}


Method 2:choose the first element as pivot, swap loop starts from second element of array


template<class T>
int partition2(T A[], int p, int q) {
    T pivot = A[p];
    int i = p;


    for (int j=p+1; j<=q; j++) {
        if (A[j]<=pivot) {
            i++;
            std::swap(A[i], A[j]);
        }
    }
    std::swap(A[i], A[p]);
   
    return i;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值