剑指offer40 最小的K个数 Java

public class MinestK40_ {
    public static void main(String[] args) {
        int[] arr = {4, 5, 1, 6, 2, 7, 3, 8};
        int k = 4;
        minestK(arr, k - 1);
        for (int i = 0; i < 4; i++) {
            System.out.println(arr[i]);
        }
    }

    private static void minestK(int[] arr, int k) {
        int low = 0, high = arr.length - 1;
        while (low < high) {
            int index = partition(arr, low, high);
            if (index == k) {
                break;
            } else if (index < k) {
                low = index + 1;
            } else {
                high = index - 1;
            }
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int temp = arr[low];
        while (low < high) {
            while (low < high && arr[high] >= temp)
                high--;
            arr[low] = arr[high];
            while (low < high && arr[low] <= temp)
                low++;
            arr[high] = arr[low];
        }
        arr[low] = temp;
        return low;
    }
}

解释:快速排序思想

猜你喜欢

转载自blog.csdn.net/weixin_43065507/article/details/99332383