int get_median(int* a, int n) {
int low = 0, high = n - 1, mid,pivot,i,j;
while (1) {
i = low, j = high;
pivot = a[i];
while (i < j) {
while (i<j && a[j] >= pivot)j--;
if (i< j)a[i] = a[j];
while (i< j && a[i] <= pivot)i++;
if (i<j)a[j] = a[i];
}
a[i] = pivot;
if (n % 2) {
if (i == n/2)return a[i];
else if (i < n/2)low=i+1;
else high=i-1;
}
else {
if (i== n / 2)return (a[i] + a[i - 1]) / 2;
else if (i == (n / 2) - 1)return (a[i] + a[i+1]) / 2;
else if (i > n / 2)high =i - 1;
else low = i + 1;
}
}
}
int getKthSmallest(int* a, int n, int k) {
int low = 0, high = n - 1, pivot,i,j;
while (1) {
i = low, j = high;
pivot = a[i];
while (i < j) {
while (i < j && a[j] >= pivot)j--;
if (i < j)a[i] = a[j];
while (i < j && a[i] <= pivot)i++;
if (i < j)a[j] = a[i];
}
a[i] = pivot;
if (i == k - 1)return a[i];
else if (i < k - 1)low = i + 1;
else high = i - 1;
}
}
利用快排中的思想,不排序,求数组中的中位数、求第K小的数
最新推荐文章于 2022-10-09 10:04:34 发布