用c++语言写一个给定由n个互不相同的数组组成的集合S以及正整数K n,试设计一个O(n)时间算法找出S中最接近S的中位数的k个数。的代码‘
时间: 2024-05-08 09:14:49 浏览: 69
```
#include <stdio.h>
#include <stdlib.h>
int cmp(const void* a, const void* b) {
return *(int*)a - *(int*)b;
}
int main() {
int n, k;
scanf("%d%d", &n, &k);
int* S = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &S[i]);
}
qsort(S, n, sizeof(int), cmp);
int left = 0, right = n - 1;
int median = (n - 1) / 2;
while (left < right && median != k - 1) {
if (median < k - 1) {
left = median + 1;
} else {
right = median - 1;
}
median = (left + right) / 2;
}
for (int i = 0; i < k; i++) {
printf("%d ", S[i + left]);
}
free(S);
return 0;
}
```
阅读全文