//find the N max numbers from an array
#include <iostream>
using namespace std;
#if 0
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int partition(int *data, int beg, int end)
{
int pos = beg;
int i = beg;
while(i < end)
{
if(data[i] >= data[end])
{
swap(data[i], data[pos]);
pos++;
continue;
}
i++;
}
swap(data[pos], data[end]);
return pos;
}
//qsort() to do partition, until find the min of N max number
int findKNumbers(int *data, int beg, int end, int k)
{
int pos = partition(data, beg, end);
int len = pos - beg + 1;
if(len == k)
return pos;
else if(len < k)
return findKNumbers(data, pos+1, end, k-len);
else
return findKNumbers(data, beg, pos-1, k);
}
#else
int find(int *data, int len, int num)
{
int total = 0;
for(int i = 0; i < len; i++)
{
if(data[i] >= num)
total++;
}
return total;
}
//binary search, until find a boundary number(!= min) of the division
int findMinOfMaxK(int *data, int len, int k)
{
int min = data[0];
int max = data[0];
for(int i = 1; i < len; i++)
{
if(data[i] < min)
min = data[i];
if(data[i] > max)
max = data[i];
}
while(max-min > 1)
{
int mid = (min + max) / 2;
int sum = find(data, len, mid);
if(sum == k)
return mid;
else if(sum > k)
min = mid;
else
max = mid;
}
return min;
}
#endif
int main()
{
int data[] = {1, 5, 2, 6, 3};
int k = 3;
#if 0
int pos = findKNumbers(data, 0, sizeof(data)/sizeof(int)-1, k);
for(int i = 0; i <= pos; i++)
cout << data[i] << " ";
cout << endl;
#else
int min = findMinOfMaxK(data, sizeof(data)/sizeof(int), k);
for(int i = 0; i < sizeof(data)/sizeof(int); i++)
if(data[i] >= min)
cout << data[i] << " ";
cout << endl;
#endif
//cout << "Hello world!" << endl;
return 0;
}
find the N max numbers from an array
最新推荐文章于 2021-11-15 10:27:41 发布