从数组中找出第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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值