找到第K小的元素(分治)
程序员文章站
2022-04-21 23:26:30
...
先做一个简单好理解的,找到第一小和第二小的数
#include<iostream>
using namespace std;
void select(int *ar,int n)
{
if(ar == NULL && n < 2)
return ;
int min1 = ar[0] < ar[1] ? ar[0]:ar[1];
int min2 = ar[0] < ar[1] ? ar[1]:ar[0];
for(int i = 2;i < n; i++)
{
if(ar[i] < min1)
{
min2 = min1;
min1 = ar[i];
}
else if(ar[i] < min2)
{
min2 = ar[i];
}
}
cout << "min1:"<< min1<<" min2:"<< min2<<endl;
}
int main()
{
int ar[]={12,23,5,65,78,25,32,15,96,99};
int len =sizeof(ar)/sizeof(ar[0]);
select(ar,len);
return 0;
}
运行结果:
找到第K小的元素:
#include<iostream>
#include<assert.h>
using namespace std;
template<class Type>
int Partition(Type *ar,int left,int right)
{
int i = left,j = right;
Type tmp = ar[i];
while(i < j)
{
while(i<j && ar[j] > tmp) --j;
if(i<j) ar[i] = ar[j];
while(i<j && ar[i] <= tmp) ++i;
if(i<j) ar[j] = ar[i];
}
ar[i] = tmp;
return i;
}
template<class Type>
const Type & Select_K(Type *ar,int left,int right,int k)
{
if(left == right && k == 1) return ar[left];
int index = Partition(ar,left,right);
int pos = index - left + 1;
if(k <= pos) return Select_K(ar,left,index,k);
else return Select_K(ar,index+1,right,k-pos);
}
template<class Type>
const Type & Select_K_Min(Type *ar,int n, int k)
{
assert(ar != NULL && n > 0 && k>=1 && k <= n);
return Select_K(ar,0,n-1,k);
}
int main()
{
int ar[] = {12,23,5,65,78,25,32,15,96,99};
int n = sizeof(ar)/sizeof(ar[0]);
for(int k = 1; k <= n; k++)
{
cout<<k<<" => "<<Select_K_Min(ar,n,k)<<endl;
}
return 0;
}
运行结果:
上一篇: C++:虚函数与多态