二十、快速排序算法——JAVA实现(递归)

一、快速排序原理:
   首先找到一个基准,一般以第一个元素作为基准(pivot),然后先从右向左搜索, 如果发现比pivot小,则和pivot交换,然后从左向右搜索,如果发现比pivot大,则和pivot交换,以此循环,一轮循环完后,pivot左边的都比它小,而右边的都比它大, 此时pivot的位置就是排好序后的最终位置,此时pivot将数组划分为左右两部分,每部分继续上面的排序操作(推荐递归方式)。

二、代码实现:
   排序前数组为:[1, 3, 2, 8, 5, 10, 22, 11, 2, 18]
   排序后数组为:[1, 2, 2, 3, 5, 8, 10, 11, 18, 22]

/**
 * 快速排序
 *
 * @author wxf
 * @date 2019/1/14 9:22
 **/
public class FastSort {

    public static void main(String[] args) {
        int[] a = {1, 3, 2, 8, 5, 10, 22, 11, 2, 18};
        quickSort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    /**
     * 快速排序
     *
     * @param arr  数组
     * @param low  基准数位置
     * @param high 数组长度
     */
    private static void quickSort(int[] arr, int low, int high) {
        int start = low;
        //arr[low]为基准数
        int key = arr[low];
        int end = high;
        while (start < end) {
            //右->左查找,找到比基准数小的值则交换位置
            while (arr[end] >= key && end > start) {
                end--;
            }
//            if (arr[end] < key) {
//                int temp = arr[end];
//                arr[end] = key;
//                arr[low] = temp;
//            }
            arr[start] = arr[end];
            //左->右查找,找到比基准数大的值则交换位置
            while (arr[start] <= key && end > start) {
                start++;
            }
//            if (arr[start] > key) {
//                int temp = arr[start];
//                arr[start] = key;
//                arr[end] = temp;
//            }
            arr[end] = arr[start];
        }
        arr[start] = key;
        //递归
        if (start > low) {
            quickSort(arr, low, start - 1);
        }
        if (end < high) {
            quickSort(arr, start + 1, high);
        }
    }
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值