直接上代码
理论部分后续再加
#include<iostream>
using namespace std;
void Swap(int &a, int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
int Partition(int a[], int p, int r)
{
int i = p-1;
int pivot = a[r];
for (int j=p;j<r;j++)
{
if (a[j]<=pivot)
{
i++;
Swap(a[i],a[j]);
}
}
Swap(a[i+1],a[r]);
return i+1;
}
void SelectSort(int a[], int p, int r)
{
for (int i=p;i<r;i++)
{
for (int j=i+1;j<=r;j++)
{
if (a[i]>a[j])
Swap(a[i],a[j]);
}
}
}
int Select(int a[], int p, int r, int k)
{
if (r-p<7)
{
SelectSort(a,p,r);
return a[p+k-1];
}
for (int i=0;i<(r-p)/5;i++)
{
int j = p+5*i;
SelectSort(a,j,j+4);
Swap(a[p+i],a[j+2]);
}
int x = Select(a,p,p+(r-p)/5-1,(r-p)/10);
int index_x = p+(r-p)/10;
Swap(a[index_x],a[r]);
int key1,key2;
key1 = Partition(a,p,r);
key2 = key1-p+1;
if (k<key2)
{
return Select(a,p,key1-1,k);
}
if (k>key2)
{
return Select(a,key1+1,r,k-key2);
}
return a[key1];
}
int main()
{
int n=35;
int a[]={17,18,19,20,21,22,23,24,25,26,27,28,29,30,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,41,46,59,90,87};
// int x = Partition(a,0,30);
// cout<<x<<endl;
cout<<endl;
cout<<"初始关键字 ";
for (int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
for (int k=1;k<=n;k++)
{
int temp;
temp=Select(a,0,n-1,k);
cout<<"第"<<k<<"小的元素是"<<temp<<endl;
cout<<endl;
}
return 0;
}