C++ qsort 实现

自己写的C++ STL Algorithm中qsort的实现如下:

void swap(void *a, void *b, int size)
{
    unsigned char *bytesOfA = reinterpret_cast<unsigned char*>(a);
    unsigned char *bytesOfB = reinterpret_cast<unsigned char*>(b);
    char tmp = 0;
    for(int i = 0; i < size; ++i)
    {
        tmp = *(bytesOfA+i);
        *(bytesOfA+i) = *(bytesOfB+i);
        *(bytesOfB+i) = tmp;
    }
}

int partition(void *base, int num, int size, int (*comparator)(const void *, const void *))
{
    int first = 0, end = num-1;
    while(first < end)
    {
        while(first < end && comparator(base+first*size, base+end*size) <= 0)
        {
            --end;
        }
        if(first < end)
        {
            swap(base+first*size, base+end*size, size);
            ++first;
        }
        while(first < end && comparator(base+first*size, base+end*size) <= 0)
        {
            ++first;
        }
        if(first < end)
        {
            swap(base+first*size, base+end*size, size);
            --end;
        }
    }
    return first;
}

void qsort(void *base, int num, int size, int (*comparator)(const void *, const void *))
{
    if(num > 0)
    {
        int pivot = partition(base, num, size, comparator);
        qsort(base, pivot, size, comparator);
        qsort(base+(pivot+1)*size, num-pivot-1, size, comparator);
    }
}
用poj2388题测试,时间、内存比用STL的qsort还要略少一点,可能是数据不大的原因吧,STL里的qsort可以对非常大的内存空间排序,应该是迭代实现的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值