从数组中找出第K大的数

 

利用改进的快排方法


public class QuickFindMaxKValue {

public static void main(String[] args) {
int[] a = {8, 3, 4, 1, 9, 7, 6, 10, 2, 5};
System.out.println(findMaxValue(a, 0, a.length - 1, 2));
}

private static int findMaxValue(int[] a, int lo, int hi, int maxValueIndex) {
if (lo >= hi) {
return -1;
}
if (maxValueIndex == a.length) {
return a[maxValueIndex];
}
int pivot = partition(a, lo, hi);
if (maxValueIndex < pivot) {
return findMaxValue(a, lo, pivot - 1, maxValueIndex);
} else if (maxValueIndex > pivot) {
return findMaxValue(a, pivot + 1, hi, maxValueIndex);
}
return pivot;
}

private static int partition(int[] a, int lo, int hi) {
int mid = (lo + hi) / 2;
if (a[mid] > a[hi]) {
swapValue(a, mid, hi);
}

if (a[lo] > a[hi]) {
swapValue(a, lo, hi);
}

if (a[lo] > a[mid]) {
swapValue(a, lo, mid);
}

int key = a[lo];
while (lo < hi) {
while (lo < hi && a[hi] > key) {
hi--;
}
a[lo] = a[hi];
while (lo < hi && a[lo] < key) {
lo++;
}
a[hi] = a[lo];
}
a[lo] = key;
return lo;
}

private static void swapValue(int[] a, int left, int right) {
if (left == right) {
return;
}
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
}
 

 

posted @ 2018-01-08 12:56  daniel456  阅读(587)  评论(0编辑  收藏  举报