排序算法之【快速排序】

目录

实现快速排序【QuickSort】并提供升序和降序方法

快速排序方法测试


实现快速排序【QuickSort】并提供升序和降序方法

public class QuickSort {
    // 排序方式:升序
    private static final int UP_SORT_TYPE = 1;

    // 排序方式:降序
    private static final int DOWN_SORT_TYPE = -1;

    /**
     * 升序排列
     *
     * @param nums:要排序的数组
     */
    public static void upSort(int[] nums) {
        if (nums == null || nums.length < 2)
            return;
        sort(nums, 0, nums.length - 1, UP_SORT_TYPE);
    }

    /**
     * 降序排列
     *
     * @param nums:要排序的数组
     */
    public static void downSort(int[] nums) {
        if (nums == null || nums.length < 2)
            return;
        sort(nums, 0, nums.length - 1, DOWN_SORT_TYPE);
    }

    /**
     * 实现排序
     *
     * @param nums:要排序的数组
     * @param low:最左下标
     * @param high:最右下标
     * @param sortType:排序方式
     */
    private static void sort(int[] nums, int low, int high, int sortType) {
        if (low < high) {
            int partitionIndex = partition(nums, low, high, sortType);
            sort(nums, low, partitionIndex - 1, sortType);
            sort(nums, partitionIndex + 1, high, sortType);
        }
    }

    private static int partition(int[] nums, int low, int high, int sortType) {
        // 找一个支点,这里支点我选择用low
        int pivot = nums[low];
        while (low < high) {
            // 根据不同的排序规则
            if (sortType == UP_SORT_TYPE) {
                // 处理升序
                while (low < high && nums[high] >= pivot) {
                    high--;
                }
                nums[low] = nums[high];
                while (low < high && nums[low] <= pivot) {
                    low++;
                }
            } else {
                // 处理降序
                while (low < high && nums[high] <= pivot) {
                    high--;
                }
                nums[low] = nums[high];
                while (low < high && nums[low] >= pivot) {
                    low++;
                }
            }
            nums[high] = nums[low];
        }
        // 这里用的是low,用high也一样,此时low==high
        nums[low] = pivot;
        return low;
    }
}

快速排序方法测试

import java.util.Arrays;

public class QuickSortTest {
    public static void main(String[] args) {
        // 测试升序
        int[] nums1 = {23, 12, 34, 42, 345, 56, 45, 34, 37, 43, 1, 23, 44, 67};
        QuickSort.upSort(nums1);
        // [1, 12, 23, 23, 34, 34, 37, 42, 43, 44, 45, 56, 67, 345]
        System.out.println(Arrays.toString(nums1));

        // 测试降序
        int[] nums2 = {23, 12, 34, 42, 345, 56, 45, 34, 37, 43, 1, 23, 44, 67};
        QuickSort.downSort(nums2);
        // [345, 67, 56, 45, 44, 43, 42, 37, 34, 34, 23, 23, 12, 1]
        System.out.println(Arrays.toString(nums2));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值