算法-快速排序

可参考https://www.cnblogs.com/sdlwlxf/p/5131793.html

0、一趟快排 单向 最简洁

int partition(int a[], int p, int r)
{
    int x = a[r];
    int i = p;
    int j = p;
    for (; j < r; ++j)
        if (a[j] < x) {
            if (i != j)
                swap(&a[i], &a[j]);
            i++;
        }
    swap(&a[i], &a[j]);
    return i;
}

1、一趟随机快速排序--双向扫描

/***************
 * 一趟随机快速排序
 * 输入 数组 长度 坐标起始 坐标终止
 * 输出 快排结束后随机关键字的下标
 **************/
int Partition(int data[], int length, int start, int end){
    //获得[start,end]之间的随机位置
    int random = rand()%(end - start + 1) + start;
    cout<<"random:"<<random<<endl;
    swap(data[0],data[random]);
    int key = data[0];
    while(start<end){
        while(start<end&&data[end]>=key)
            end--;
        data[start]=data[end];
        while(start<end&&data[start]<=key)
            start++;
        data[end]=data[start];
    }   
    data[start]=key;
    for(int i=0;i<length;i++)
        cout<<data[i]<<' ';
    cout<<endl;
    return start;
}

2.一趟随机快速排序——单向扫描

/******
 *减少循环次数的一趟 随机 快速排序
 *****/
int Partition(int data[], int length, int start, int end)
{
    if(data == nullptr || length <= 0 || start < 0 || end >= length)
        throw new std::exception("Invalid Parameters");

    int index = rand()%(end - start + 1) + start;
    Swap(&data[index], &data[end]);

    int small = start - 1;
    for(index = start; index < end; ++ index)
    {
        if(data[index] < data[end])
        {
            ++ small;
            if(small != index)
                Swap(&data[index], &data[small]);
        }
    }

    ++ small;
    Swap(&data[small], &data[end]);

    return small;
}

3.第一种方式的递归快速排序

/***************
 *递归快速排序
 **************/
void Partition_all(int data[], int length, int start, int end){
    //获得[start,end]之间的随机位置
    //int random = rand()%(end - start + 1) + start;
    //cout<<"all--andom:"<<random<<endl;
    //swap(data[0],data[random]);
    if(start>=end)
        return;
    int t_start = start;
    int t_end = end;
    int key = data[start];
    while(start<end){
        while(start<end&&data[end]>=key)
            end--;
        data[start]=data[end];
        while(start<end&&data[start]<=key)
            start++;
        data[end]=data[start];
    }
    data[start]=key;
    /*
    for(int i=0;i<length;i++)
        cout<<data[i]<<' ';
    cout<<endl;
    */
    Partition_all(data,length,t_start,start-1);   //注意递归范围 不包括已经排序完成的那个基准值元素
    Partition_all(data,length,start+1,t_end);
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值