Merge pull request #266 from wangjunwei87/patch-1

找到一组数据的第K大元素
This commit is contained in:
wangzheng0822 2019-03-11 09:58:34 +08:00 committed by GitHub
commit e0cd3f758d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,51 @@
package sort;
/**
* @author wangjunwei87
* @since 2019-03-10
*/
public class KthSmallest {
public static int kthSmallest(int[] arr, int k) {
if (arr == null || arr.length < k) {
return -1;
}
int partition = partition(arr, 0, arr.length - 1);
while (partition + 1 != k) {
if (partition + 1 < k) {
partition = partition(arr, partition + 1, arr.length - 1);
} else {
partition = partition(arr, 0, partition - 1);
}
}
return arr[partition];
}
private static int partition(int[] arr, int p, int r) {
int pivot = arr[r];
int i = p;
for (int j = p; j <= r - 1; j++) {
if (arr[j] < pivot) {
swap(arr, i, j);
i++;
}
}
swap(arr, i, r);
return i;
}
private static void swap(int[] arr, int i, int j) {
if (i == j) {
return;
}
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}