I have a circular queue of ordered items. I want to know if an item with the value of “x” is in it.
What is the best way (algorithm) to do this?
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 can access each item by index, you can use a binary search.
If you can only see the first item, you need to pop them from the queue until the search key is lower than the key of the item you just popped. Since the queue is sorted, you can stop as soon as you know that the key can’t be in the queue anymore.
[EDIT] Since you can access by index: Warp the circular queue in an object which maps it to an “array” (i.e. with a method
get(index)whereindexruns from0tolength-1and which internally does((index+start)%length).That way, you can apply the binary search without thinking about the actual data layout.