c/c++找第k小元素代码(非排序)

来源:互联网 发布:贺卫方反对网络实名制 编辑:程序博客网 时间:2024/05/29 18:24

不用排序,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;}
0 0
原创粉丝点击