Find the K-th largest number

Title description

There is an array of integers. Please find the K-th largest number in the array according to the idea of ​​quick sort.
Given an integer array a, given its size n and the K you are looking for (K is between 1 and n), please return the Kth largest number to ensure that the answer exists.

Example
input:

[1,3,5,2,2],5,3

Output:

2

Idea 1: The
first thing that comes to mind is to sort the array first, and then output the subscript of the Kth number from the bottom = the length of the array-k;

So the question is directly decomposed into the question of how to sort the array. The first is to directly use the official Java API, Arrays.sort(array); for sorting. Although the answer obtained in this way is correct, the question requires It is the idea of ​​using fast sorting.

 public static  int findKth(int[] a, int n, int K) {
    
    
        if(K>n)
            return 0;
        Arrays.sort(a);
        return a[n-K];
    }

Idea 2:
Use the idea of
quick sorting to sort array elements: The idea of ​​quick sorting is mainly divided into three parts:
(1) Find the benchmark value;
(2) Partition part (Hoare method, digging method, front and back traversal method)
(3 ) ) Sort the left and right sub-intervals separately;

//交换两个数字
public static void swap(int[] array,int index1,int index2){
    
    
        int tmp=array[index1];
        array[index1]=array[index2];
        array[index2]=tmp;
    }
    //partition部分
    public static int partition(int[] array,int lowIndex,int highIndex){
    
    
        int leftIndex=lowIndex;
        int rightIndex=highIndex;
        //作为基准值的是最左边的一个数
        int key=array[lowIndex];
        while(leftIndex<rightIndex){
    
    
            while(leftIndex<rightIndex&&array[rightIndex]>=key){
    
    
                rightIndex--;
            }
            while(leftIndex<rightIndex&&array[leftIndex]<=key){
    
    
                leftIndex++;
            }
            //否则就进行交换
            swap(array,leftIndex,rightIndex);


        }
        swap(array,lowIndex,leftIndex);
        return leftIndex;
    }
    //快排具体实现部分
    public static void quickSortInternal(int[] array,int lowIndex,int rightIndex){
    
    
        int size=rightIndex-lowIndex+1;
        if(size<=1){
    
    
            return ;
        }
        //对左右两个区间分别进行排序
        int keyIndex=partition(array,lowIndex,rightIndex);
        quickSortInternal(array,lowIndex,keyIndex-1);
        quickSortInternal(array,keyIndex+1,rightIndex);
    }
    public static void quickSort(int[] array){
    
    
        quickSortInternal(array,0,array.length-1);

    }

    public static  int findKth2(int[] a, int n, int K) {
    
    
        //利用快排先进行数组元素的排序
        quickSort(a);
        return a[n-K];
    }

Guess you like

Origin blog.csdn.net/m0_46551861/article/details/115023449