算法-快速排序

算法思路

  1. 每次遍历将比第一个数小的移动到这个数的左边,将比这个数大的数移到右边,得到这个数的最终位置
  2. 对得到的两个未排序的子数组继续排序

伪代码

  1. 以arr[0]为基准,i=0,j=arr.length - 1
  2. 逆序比较,第一个比基准小的数移动到i的位置
  3. 正序比较,第一个比基准大的数移动到j的位置
  4. 重复上述步骤,直到i=j,令arr[i]为基准的值
  5. 重复以上步骤,直到确认所有数的位置

具体代码

// quicksort
// sort arr[] from low to high by quicksort
// int [] arr
// int low: the start index
// int high: the end index
void QuickSort(int* arr, int low, int high) {
    if (NULL == arr) return;
    if (high <= low) return;
    int ori_low = low; // the origin low index
    int ori_high = high; // the origin high index
    int base = arr[low]; // the basekey
    while (low < high) {
        while (low < high && arr[high] >= base) high--;
        if (arr[high] < base) arr[low] = arr[high];
        while (low < high && arr[low] <= base) low++;
        if (arr[low] > base) arr[high] = arr[low];
    }
    arr[low] = base;
    if (low > ori_low) {
        QuickSort(arr, ori_low, low - 1);
    }
    if (low < ori_high) {
        QuickSort(arr, low + 1, ori_high);
    }
}

算法分析

  1. 时间复杂度:O(nlog2(n))
  2. 非稳定排序
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值