从数组中找出第K大的数

利用改进的快排方法

public class QucikFindMaxK {
    static void swap(int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

//   升序排列,比arr[pivotIndex]值小的数都在arr[pivotIndex]左边,大的数都在右边
    static int partition(int arr[], int left, int right, int pivotIndex) {
        int storeIndex = left;  //storeIndex表示左边排好序的最后一个位置
        int pivotValue = arr[pivotIndex];
        swap(arr, pivotIndex, right); //先把pivoit位置的值放到最右边right
        for (int i = left; i < right; i++) {
            if (arr[i] > pivotValue) {
                swap(arr, i, storeIndex);
                storeIndex++;
            }
        }
        swap(arr, storeIndex, right); //将最右边的pivotValue交换到storeIndex后面,此时整个数组满足storeIndex左边的值大,右边的值小
        return storeIndex;
    }

    static int findKMax(int arr[], int left, int right, int k) {
        int pivotIndex = left + 1;
        int nRet = partition(arr, left, right, pivotIndex);
        if (nRet < k) return findKMax(arr, nRet + 1, right, k);//第K大值在pivot的右边,所以从pivot后面查找
        else if (nRet > k) return findKMax(arr, left, nRet - 1, k);//第K大值在pivot的左边,所以从pivot前面查找
        return nRet;
    }

    public static void main(String[] args) {
        int arr[] = {8, 3, 4, 1, 9, 7, 6, 10, 2, 5};
        int nRet = findKMax(arr, 0, 9, 1);//MaxValued对应的的k为0
        System.out.println(" Max Number is" + arr[nRet]);

    }
}
原文地址:https://www.cnblogs.com/wzj4858/p/8242138.html