不用排序,c/c++找第k小元素代码
编译环境vs2013,源代码如下:
#include<iostream>
using namespace std;
void Sort(int k,int a[],int start,int end)
{
int s = a[start];
int t=start;
int m = 0;
for (int i = start+1; i < end+1; i++)
{
if (s > a[i])
{
t++;
if (i != t)
{
m = a[i];
a[i] = a[t];
a[t] = m;
}
}
}
a[start] = a[t];
a[t] = s;
//cout << t << " ";
if (t == k-1)
{
//cout << endl;
cout << s<<endl;
}
else if (t > k-1)
{
Sort(k, a, start, t-1);
}
else
{
Sort(k, a, t+1, end);
}
}
int main()
{
int N,K,a[100];
cout << "请输入N" << endl;
cin >> N;
for (int i = 0; i < N; i++)
{
cin >> a[i];
}
cout << "请输入K" << endl;
cin >> K;
Sort(K,a,0,N-1);
system("pause");
return 0;
}