赞
踩
#include <iostream> #include <vector> #include <algorithm> using namespace std; int findKthSmallestElement(vector<int> vt, int k); int main() { //input freopen("findKthSmallestElementInput.txt", "r", stdin); int n, k; vector<int> vt; scanf("%d", &n); for(int i = 0; i < n; i++) { scanf("%d", &k); vt.push_back(k); } scanf("%d", &k); //process int ans = findKthSmallestElement(vt, k); //output freopen("findKthSmallestElementOutput.txt", "w", stdout); printf("第%d小的数据元素为:%d", k, ans); } int findKthSmallestElement(vector<int> vt, int k) { int size = vt.size(); if(size < 75) { //数据规模小于75,直接快排找第K小的值 sort(vt.begin(), vt.end()); return vt[k - 1]; } vector<int> medium; //中间值数据 int numEle = 5; //每组numEle个数据 for(int i = 0; i < size; i += numEle) { vector<int> temp; for(int j = i; j < i + numEle && j < size; j++) { temp.push_back(vt[j]); } if(temp.size()) medium.push_back(findKthSmallestElement(temp, 1 + temp.size()/2)); } int x = findKthSmallestElement(medium, 1 + medium.size()/2); //找到中位数 vector<int> S1, S2; //分成两部分 for(int i = 0; i < size; i++){ if(vt[i] <= x) S1.push_back(vt[i]); else S2.push_back(vt[i]); } if(k <= S1.size()) return findKthSmallestElement(S1, k); else return findKthSmallestElement(S2, k-S1.size()); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。