Comment Comment by dzorz Here is a solution in C++. It reads K and then N numbers from stdin and then prints K largest.The complexity of nth_element is O(N). #include <algorithm> #include <vector> #include <iostream> #include <iterator> using namespace std; int main() { int K; cin >> K; vector<int> numbers((istream_iterator<int>(cin)), istream_iterator<int>()); nth_element(numbers.begin(), numbers.begin() + K, numbers.end(), greater<int>()); for (int i = 0; i < K; ++i) { cout << numbers[i] << ' '; } cout << '\n'; } Input: 5 1 9 1 3 7 8 2 11 2 5 5 9 1 7 Output: 7 9 9 11 8 Note: the output is not sorted. parent dzorz 15 years ago
The complexity of nth_element is O(N).
Input: Output: Note: the output is not sorted.