手写数组二分排序

1. 需求

对数组进行升排序

2. 方案

二分排序:时间复杂度是O(nlgn),是最高效的排序方式的一种;

代码

    /**
     * 升序排列数组
     *
     * @param arr   原始数组
     * @param start 数组需要排序的起始index
     * @param end   数组需要排序的终止index
     */
    private static void quickSort2(int[] arr, int start, int end) {

        // 最简情况
        if (start == end - 1) {
            if (arr[start] > arr[end]) {
                int temp = arr[start];
                arr[start] = arr[end];
                arr[end] = temp;
            }
            return;
        }
        // 一般情况
        else if (start < end) {
            normal(arr, start, end);
        }

    }

    /**
     * 升序排列数组
     *
     * @param arr   原始数组
     * @param start 数组需要排序的起始index
     * @param end   数组需要排序的终止index
     */
    private static void normal(int[] arr, int start, int end) {
        int pivot = arr[start];
        int low = start;
        int high = end;
        while (low < high) {
            // 比pivot大,掠过,遇到比pivot小的,甩到左边;
            while (low < high && pivot <= arr[high]) {
                high--;
            }
            arr[low] = arr[high];

            // 比pivot小,掠过,遇到比pivot大的,甩到右边;
            while (low < high && arr[low] < pivot) {
                low++;
            }
            arr[high] = arr[low];
        }
        // 最后将预先标记的定值放回
        arr[low] = pivot;

        // 数组分成两节后分别进行递归;
        quickSort2(arr, start, low - 1);
        quickSort2(arr, low + 1, end);
    }

3. 测试结果

    public static void main(String[] args) {

        int num = 1_000_000;
        int[] ints = new int[num];

        for (int i = 0; i < num; i++) {
            ints[i] = new Random().nextInt(10000);
        }
        long start = System.currentTimeMillis();
//        Arrays.sort(ints); // 190 200 245 302 211 // jdk 自带的排序方法,百万级数据,连续测试5次,花费的毫秒数
        quickSort2(a, 0, a.length - 1); // 253 199 221 238 213,当前方法,同条件测试结果,效率接近sort()
        System.out.println("用时:" + (System.currentTimeMillis() - start) + " ms");

    }
发布了93 篇原创文章 · 获赞 20 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/leinminna/article/details/102909173