常用算法——快速排序

1.什么是快速排序

  1. 选定数组中一个数为基准数(此文以数组第一个数作为基准数,个人习惯如此)。
  2. 分别从最左和最右遍历数组,将大于基准数的数放在其右边,小于基准数的数放在其左边。
  3. 递归方式重复步骤2,直到各区间只有一个数或为空。

    *快速排序被认为是所有O(N*logN)排序算法中效率最高的。

2.时间复杂度&空间复杂度

最好情况:O(N*logN)
平均情况:O(N*logN)
最坏情况:O(N^2)
空间占用S(1),只需花费常数级的空间。

3.代码实现(Java实现)

public class QuickSort {
    public void sort(int temp[]) {
        quickSort(temp, 0, temp.length - 1);
    }

    private void quickSort(int[] temp, int low, int high) {
        if (low < high) {
            int des = getDes(temp, low, high);
            quickSort(temp, low, des-1);
            quickSort(temp, des+1, high);
        }
    }

    private int getDes(int[] temp, int low, int high) {
        int t = temp[low]; //缓存基准数
        while (low < high) {
            while (low < high && temp[high] > t) {
                high--;
            }
            temp[low] = temp[high];

            while (low < high && temp[low] < t) {
                low++;
            }
            temp[high] = temp[low];
        }
        temp[low] = t; //将基准数赋值给空缺位
        return low;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值