There are N values in the array, and one of them is the smallest value. How can I find the smallest value most efficiently?
Share
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.
If they are unsorted, you can’t do much but look at each one, which is O(N), and when you’re done you’ll know the minimum.
Pseudo-code:
A better way reminded by Ben to me was to just initialize small with the first element:
The above is wrapped in the algorithm header as std::min_element.
If you can keep your array sorted as items are added, then finding it will be O(1), since you can keep the smallest at front.
That’s as good as it gets with arrays.