八大排序算法之快速排序

八大排序算法之快速排序


八大排序算法每一种都是必须掌握的,不过快速排序是我们必须掌握很熟练并且是面试中被问到的最多次的排序算法。面试时会被面试官问到快速排序实现的原理,会问到给定序列的时间复杂度等等。


快速排序也是分治算法的一种,何为分治算法?请百度,哦不,谷歌一下先。。。Talk is cheap,show you the code!

public class Test9{
    /**以下标low对应的元素为基准 将比它小的 排在他的前面 反之排在他的后面 最后返回这个基准元素的下标*/
    public static int ThatIndex(int []a, int low,int high){
        int tmp = 0;
        int thatvalue= a[low];//取出基准元素
        while(low < high){
            while(low < high && a[high] >= thatvalue ) --high;//找到一个比基准元素小的 停下 和基准值元素交换位置
            tmp= a[low];a[low]= a[high];a[high]= tmp;
            while(low < high && a[low] <= thatvalue  ) ++low;//找到一个比基准元素大的 停下 与基准元素交换位置
            tmp= a[low];a[low]= a[high];a[high]= tmp;
        }
        //最后返回基准元素对应的下标
        return low;
    }
    /**快速排序 递归查找基准元素 把小值放在它的前面 反之放在后面 直到排序完成 结束函数*/
    public static void QuickSort(int []a, int low,int high){
        if(low < high){
            int thatindex= ThatIndex(a, low, high);
            QuickSort(a, low, thatindex-1);
            QuickSort(a, thatindex+1, high);
        }
    }
    public static void main(String[] args) {
        int []a= new int[10];
        for (int i = 0; i < a.length; i++) {
            Scanner c= new Scanner(System.in);
            a[i]= c.nextInt();
        }
        QuickSort(a, 0, a.length-1);
        for (int i : a) {
            System.out.print(i+"  ");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值