编辑代码

class Main {

    public static int findKthLargest(int[] nums, int k) {
    int left = 0, right = nums.length - 1;
    while (left <= right) {
        int pivotIndex = partition(nums, left, right);
        if (pivotIndex == k - 1) {
            return nums[pivotIndex];
        } else if (pivotIndex < k - 1) {
            left = pivotIndex + 1;
        } else {
            right = pivotIndex - 1;
        }
    }
    return -1;
}

    private static int partition(int[] nums, int left, int right) {
        int pivot = nums[left];
        int i = left + 1, j = right;
        while (i <= j) {
            if (nums[i] < pivot && nums[j] > pivot) {
                swap(nums, i++, j--);
            }
            if (nums[i] >= pivot) {
                i++;
            }
            if (nums[j] <= pivot) {
                j--;
            }
        }
        swap(nums, left, j);
        return j;
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        int []array = {1,7,9,8,2,11,50,2};
        int k = findKthLargest(array, 4);
		System.out.println("无序数组array中第4大元素 = " + k);
	}
}