There are 100 numbers present in an array and I need to find out the average of top 5 highest numbers among them.
Also in the same way the average of top 5 lowest numbers among them. How could I go about doing it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use Hoare’s select algorithm (or the median of medians, if you need to be absolutely certain of the computational complexity), then add the top partition (and divide by its size to get the average).
This is somewhat faster than the obvious method of sorting instead of partitioning — partitioning is (
O(N)) where sorting isO(N log(N) ).Edit: In C++, for real code (i.e., anything except homework where part of the requirement is to do the task entirely on your own) you can use
std::nth_elementto partition the input into the top 5 and everything else.Edit2: Here’s another quick demo to complement @Nils’, but this one in full C++11 regalia (so to speak):