【算法】寻找第K个最小的数

1 直接上源码实现


public class QuickSort {

    private static final int[] array = new int[]{4,11,21,31,5,6,7,8,9,0};


    public static int quickSortFindK(int[] array, int begin, int end, int k){

        if(begin >= end){
            return array[begin];
        }
        int partition = partitionR(array, begin, end);
        if(k == partition){
            return array[k];
        }
        if(k < partition) {
            return quickSortFindK(array, begin, partition - 1, k);
        }
        return quickSortFindK(array, partition + 1, end, k);

    }


    private static int partitionTwoPoint(int[] array, int begin, int end) {
        int pivot = array[begin];
        while(begin < end){
            // 不包含等值
            while(begin < end && array[end] > pivot){
                end--;
            }
            // 收集左侧集合
            array[begin] = array[end];

            // 包含等值 左侧划分全集
            while(begin < end && array[begin] <= pivot){
                begin++;
            }
            // 收集右侧集合
            array[end] = array[begin];
        }
        array[begin] = pivot;
        return begin;
    }

    // [O] [<] [<] [<] [>] [>] [>] [>]
    // [<] [<] [<] [O] [>] [>] [>] [>]
    // 3 begin 6 head
    private static int partitionR(int[] array, int begin, int end) {
        int pivot = array[begin];
        int head = begin + 1;// 头结点
        for(int i = head; i <= end; i++){
            if(array[i] <= pivot){
                swap(array, i, head);
                head++;
            }
        }
        swap(array, begin, head-1);
        return head-1;
    }

    private static int partition(int[] array, int begin, int end) {
        int head = begin + 1;
        int nextIndex = head;
        while (nextIndex <= end) {
            if (array[nextIndex] <= array[begin]) {
                swap(array, nextIndex, head);
                head++;
            }
            nextIndex++;
        }
        swap(array, begin, head-1);
        return head-1;
    }





    public static void main(String[] args) {
        int i1 = quickSortFindK(array, 0, array.length - 1, 9);
        System.out.println(i1);
    }

    private static void swap(int[] array, int head, int tail) {
        int temp = array[head];
        array[head] = array[tail];
        array[tail] = temp;
    }

}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页