10种排序算法六:快速排序 - 不稳定

快速排序



/**
 * 排序算法六:快速排序 - 不稳定
 * 【思想】数组中随机取一个元素与最后一个元素进行交换,并设置为初始轴。
 * 定义左右边界,同时向中间移动,直到左边的值小于左边轴值,并且右边的值大于轴值,此时将两个数进行交换,再将轴值与最左边的值位置进行交换,并返回轴下标。
 * 以新轴下标为分界点,分别向左向右进行递归。
 * 时间复杂度:n*logN
 * 空间复杂度:logN
 */
public class QuickSort {

    public static void main(String[] args) {
        int[] arr = {0, 9, 6, 11, 3, 5, 12, 8, 10, 15, 14, 4, 1, 13, 7, 0};
        int arrLength = arr.length - 1;
        System.out.println("初始值:" + Arrays.toString(arr));
        sort(arr, 0, arrLength);
        System.out.println("排后值:" + Arrays.toString(arr));
    }

    public static void sort(int[] arr, int leftBound, int rightBound) {
        if (leftBound >= rightBound) return;
        int oldPivotIndex = partition(arr, leftBound, rightBound);
        sort(arr, leftBound, oldPivotIndex - 1);
        sort(arr, oldPivotIndex + 1, rightBound);
    }

    /**
     * 单轴快排
     *
     * @param arr
     * @param leftBound  左边界
     * @param rightBound 右边界
     * @return 返回交换轴后,旧轴所在的位置
     */
    public static int partition(int[] arr, int leftBound, int rightBound) {
        int pivot = arr[rightBound];
        int left = leftBound;
        int right = rightBound - 1;

        while (left <= right) { // 如果加=号,那么需要把1处代码加上。当left与right相等时,并不会走循环,会导致pivot直接会与left进行交换。
            while (left <= right && arr[left] <= pivot) left++;
            while (left <= right && arr[right] > pivot) right--;
            if (left < right) swap(arr, left, right);
        }
//   //1.     if (arr[left] >pivot)    // 左边值比右边界值大,才进行交换
        swap(arr, left, rightBound);
        return left;
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    /**
     * 双轴快排:实现极其复杂,参考Arrays.sort();
     */
    public static void partitionTwo(){

    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值