Skip to content

Commit

Permalink
Merge pull request wangzheng0822#266 from wangjunwei87/patch-1
Browse files Browse the repository at this point in the history
找到一组数据的第K大元素
  • Loading branch information
wangzheng0822 authored Mar 11, 2019
2 parents 8eb1cb1 + c486abb commit e0cd3f7
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions java/12_sorts/KthSmallest.java
Original file line number Diff line number Diff line change
@@ -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;
}
}

0 comments on commit e0cd3f7

Please sign in to comment.