给定一个数组A,求出第k小的元素。
这是一个次序选择问题,求解方法多种,此处介绍在快排的思想上进行改造的分治算法。
数组A,起始位置p,终止位置r,要查找的第k小元素
选取固定位置主元
情况1:k=q-p+1,A[q]为数组第k小元素
情况2:k<q-p+1,在A[p..q-1]中寻找第k小元素
情况3:k<q-p+1,在A[q+1..r]中寻找第k-(q-p+1)小元素
初始数组:A[16]={21,17,37,28,13,14,22,52,40,24,48,4,47,8,42,18};
#include<iostream>
using namespace std;
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
int Partition(int A[],int p,int r) //数组A,起始位置p,终止位置r
{
int x=A[r];
int i=p-1;
for(int j=p;j<=r-1;j++)
{
if(A[j]<=x)
{
swap(A[i+1],A[j]);
i++;
}
}
swap(A[i+1],A[r]);
return i+1; //划分位置i+1
}
int Selection(int A[],int p,int r,int k) //数组A,起始位置p,终止位置r,要查找的第k小元素
{
int q=Partition(A,p,r);
int x;
if(k==q-p+1)
x=A[q];
if(k<q-p+1)
x=Selection(A,p,q-1,k);
if(k>q-p+1)
x=Selection(A,q+1,r,k-(q-p+1));
return x;
}
int main()
{
int A[16]={21,17,37,28,13,14,22,52,40,24,48,4,47,8,42,18};
cout<<Selection(A,0,15,8)<<endl;
}
基于快速排序算法,为了提高效率,减少运行时间,利用随机函数每次随机选取主元,因此可对代码稍微进行修改,如下:
#include<iostream>
#include <stdlib.h>
using namespace std;
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
int Partition(int A[],int p,int r) //数组A,起始位置p,终止位置r
{
int x=A[r];
int i=p-1;
for(int j=p;j<=r-1;j++)
{
if(A[j]<=x)
{
swap(A[i+1],A[j]);
i++;
}
}
swap(A[i+1],A[r]);
return i+1; //划分位置i+1
}
int Randomized_Partition(int A[],int p,int r)
{
int s=p + rand()%(r-p+1);//随机产生p ~ r之间的随机数
swap(A[s],A[r]);
int q=Partition(A,p,r);
return p;
}
int Selection(int A[],int p,int r,int k) //数组A,起始位置p,终止位置r,要查找的第k小元素
{
int q=Randomized_Partition(A,p,r);
int x;
if(k==q-p+1)
x=A[q];
if(k<q-p+1)
x=Selection(A,p,q-1,k);
if(k>q-p+1)
x=Selection(A,q+1,r,k-(q-p+1));
return x;
}
int main()
{
int A[16]={21,17,37,28,13,14,22,52,40,24,48,4,47,8,42,18};
cout<<Selection(A,0,15,8)<<endl;
}