public class Algorithm {

public static void main(String[] args) {

int[] arr = {3,2,3,1,2,4,5,5,6};
System.out.println(new Solution().findKthLargest(arr, 4));

}
}

class Solution {
public int findKthLargest(int[] nums, int k) {

int temp = 0;

/**
* 数组排序后的第k个最大的元素,不是第k个不同的元素,因此就是数组排好序从右往左数的第k个元素
*/
int target = nums.length - k;
sort(nums, 0, nums.length - 1, target, temp);

return nums[nums.length - k];
}

public static void sort(int[] arr, int left, int right, int target, int temp){

int p = partition(arr, left, right, temp);

/**
* 使用双路排序法,如果返回的索引刚好是目标,就直接return
* 否则只用判断一个区间
*/
if (p == target){
return;
}
else if (target < p) {
sort(arr, left, p - 1, target, temp);
}
else {
sort(arr, p + 1, right, target, temp);
}
}

public static<E extends Comparable<E>> int partition(int[] arr, int left, int right, int temp) {

int i = left + 1;
int j = right;

while (i <= j){

if (arr[i] < arr[left]){
i++;
}
else if (arr[j] > arr[left]){
j--;
}
else {
swap(arr, i, j);
i++;
j--;
}
}

swap(arr, j, left);

return j;
}

public static void swap(int[] arr, int i, int j) {

int temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}