题干
有一个整数数组,请你根据快速排序的思路,找出数组中第K大的数。 给定一个整数数组a,同时给定它的大小n和要找的K(K在1到n之间),请返回第K大的数,保证答案存在。
话不多说直接上代码
import java.util.*;
public class Finder {
public int findKth(int[] a, int n, int K) {
quickSort(a, 0, n - 1);//排完序是从小到大的序列
return a[n-K];
}
private static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// 找寻基准数据的正确索引
int index = getIndex(arr, low, high);
quickSort(arr, low, index - 1);//基准元素之前的进行排序
quickSort(arr, index + 1, high);//基准元素之后的进行排序
}
}
private static int getIndex(int[] arr, int low, int high) {
// 基准数据
int tmp = arr[low];
while (low < high) {
// 当队尾的元素大于等于基准数据时,向前挪动high指针
while (low < high && arr[high] >= tmp) {
high--;
}
// 如果队尾元素小于tmp了,需要将其赋值给low
arr[low] = arr[high];
// 当队首元素小于等于tmp时,向前挪动low指针
while (low < high && arr[low] <= tmp) {
low++;
}
// 当队首元素大于tmp时,需要将其赋值给high
arr[high] = arr[low];
}
// 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
// 由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
arr[low] = tmp;
return low; // 返回tmp的正确位置
}
}
这是今天在牛客上看到的一道面试题,主要还是考察对快速排序的理解
以前对快速排序很朦胧今天至少深入了解了一下
在写的时候我直接套用了这位大神写的代码
https://blog.youkuaiyun.com/nrsc272420199/article/details/82587933