排序算法:快速排序

一、快速排序的步骤:

* 首先选取一个值(一般选取数组第1个值7 )作为参考值,例如数组 :{7 ,5 ,9, 6 ,3}   


* 把数组分成 {3,5}   和  {7,9}   每个数组再次递归排序。


public class FastSort {

    public static void main(String[] args) {
        System.out.println("Hello World");
        int[] a = {7 ,5 ,9, 6 ,3};
        int start = 0; //起始位置
        int end = a.length - 1;//结束位置
        FastSort.sort(a, start, end);
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }

    }

    public static void sort(int[] a, int low, int high) {
        int start = low;//开始节点
        int end = high;//结束节点
        int key = 0;
     if(low < a.length - 1){
       key =  a[low];//参考值
     }
        while (end > start) {
            //从后往前比较
            while (end > start && a[end] >= key)  //如果没有比关键值小的,比较下一个,直到有比关键值小的交换位置,然后又从前往后比较
                end--;
            if (a[end] <= key) {
                int temp = a[end];
                a[end] = a[start];
                a[start] = temp;
            }
            //从前往后比较
            while (end > start && a[start] <= key)//如果没有比关键值大的,比较下一个,直到有比关键值大的交换位置
                start++;
            if (a[start] >= key) {
                int temp = a[start];
                a[start] = a[end];
                a[end] = temp;
            }
            //此时第一次循环比较结束,关键值的位置已经确定了。左边的值都比关键值小,右边的值都比关键值大,但是两边的顺序还有可能是不一样的,进行下面的递归调用

            for (int i = 0; i < a.length; i++) {
                System.out.print(a[i]);
                System.out.print(",");
            }
            System.out.println(" start: "+start+" end: "+end);
        }
        //递归
        if (start > low) {
            //System.out.println("left: "+ low+": "+(start - 1));
            sort(a, low, start - 1);//左边序列。第一个索引位置到关键值索引-1
        }
        if (end < high) {
            //System.out.println("right: "+ (end+1)+": "+high);
            sort(a, end + 1, high);//右边序列。从关键值索引+1到最后一个
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值