Possible Duplicate:
finding all numbers less than x in a BST
How would I modify a binary search to find the number of numbers in a sorted array that are less than a certain number?
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 you have an already sorted array of numbers simply find the insertion point for your item in the sorted array usng a binary search algorithm. The index of the insertion point gives you the number of elements that are less than your target number.
In your comments you raised two good questions:
To handle this you keep searching until you find the point where the number should be if it were present, that is the index where the current element is greater than x and the previous element is less than x.
To handle this, instead of stopping when you first find an element, continue searching until you lower bound and upper bound meet. If you hit a value that is equal to x treat it in the same way as if you found a number that was too high and continue bisecting.