您的位置:首页 > 其它

二分搜索问题(未理解)

2016-01-14 21:23 337 查看
Haruhi Suzumiya is always interested with extraterrestrials, supernaturals, people who pass through the time from future, and other cool things! But she’s now feel bored with the most interesting thing, the second most interesting thing, the thired …, and the K-1th most interesting thing! So she want you to help her find the Kth moth interesting thing.

You are required to write a funcion to do this job:

int iLoveYukiNagato(int *num, const int size, const int K);

// return the Kth largest number in the array “num” which contains “size” numbers.

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 1000000

int iLoveYukiNagato(int *, const int, const int);

int main() {
unsigned int seed;
scanf("%u", &seed);
int i, size, T;
int *num = (int*)malloc(MAXSIZE*sizeof(size));
for (T = 0; T < 45; ++T) {
size = 1 + rand_r(&seed)%MAXSIZE;
for (i = 0; i < size; ++i)
num[i] = rand_r(&seed);
printf("%d\n", iLoveYukiNagato(num, size, 1+rand_r(&seed)%size));
}
free(num);
return 0;
}

int iLoveYukiNagato(int *num, const int size, const int k) {
int x = num[size >> 1];
int i = 0, j = size-1, t;
do {
while (num[i] > x)
++i;
while (num[j] < x)
--j;
if (i <= j) {
t = num[i];
num[i] = num[j];
num[j] = t;
++i;
--j;
}
} while (i <= j);
if (j+1 < k && k <= i)
return num[k-1];
if (j+1 >= k)
return iLoveYukiNagato(num, j+1, k);
return iLoveYukiNagato(num+i, size-i, k-i);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: