快速排序-递归和非递归的实现

快速排序主要就是partition的操作。

排序主体

/* 递归的实现。A[] -->要排序的数组, s  --> 开始位置, e  --> 结束位置 */
void quickSort(int arr[], int s, int e)
{
    if (s < e)
    {
        int p = partition(arr, s, e); /* Partitioning index */
        quickSort(arr, s, p - 1);
        quickSort(arr, p + 1, e);
    }
}

划分

//普通划分操作。以最后一个元素 arr[e]作为基准
int partition(int arr[], int s, int e){
    int i = s-1;
    for(int j = s; j<e; j++){
        if(arr[j] <= arr[e]){
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[e], arr[i+1]);
    return i+1;
}

将序列划分为三部分:小于基准元素(i指向最后一个小于基准的元素)、大于基准元素((i,j))和未知元素部分(j指向第一个未知元素)。

划分-随机版本

//随机化的划分操作。已最后一个元素 arr[e]作为基准
int partitionRandom(int arr[], int s, int e){
    //取得一个随机的下标
    int randomIndex = rand() % (e-s+1) + s;
    swap(arr[e], arr[randomIndex]);
    int i = s-1;
    for(int j = s; j<e; j++){
        if(arr[j] <= arr[e]){
            i++;
            swap(arr[i], arr[j]);
        }
    }
    swap(arr[e], arr[i+1]);
    return i+1;
}

划分–另一种实现

//划分操作的 第二种实现
int partition2(int * arr, int start, int end) {
    int i = start;//指向开头
    int j = end + 1;//指向结尾
    int pivot = arr[start];
    while(true){
       while( i<end && arr[++i] < pivot);//从前到后  第一个比 基准(x)大的数。 j指向该数
       while(j>start && arr[--j] > pivot);//从后向前找到第一个比 基准(x)小的数。i指向该数
        if(i >= j)
            break;
        swap(arr[i], arr[j]);
    }
    arr[start] = arr[j];
    arr[j] = pivot;
    return j;
}

非递归实现

//快速排序的非递归实现
void quicksortIterative(int arr[],int s, int e){
    stack<int> sta;
    sta.push(s);
    sta.push(e);
    while(!sta.empty()){
        int end = sta.top(); sta.pop();
        int start = sta.top(); sta.pop();
        int mid = partitionRandom(arr, start, end);
        //只有元素个数大于1的时候,才放入栈中
        if(mid-1 > start){
            sta.push(start);
            sta.push(mid-1);
        }
        if(end > mid+1){
            sta.push(mid-1);
            sta.push(end);
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值