首页 > 编程 > C++ > 正文

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

2019-11-06 07:59:23
字体:
来源:转载
供稿:网友

不用排序,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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选