Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding an item in a circular queue?

Tags:

queue

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?

like image 275
Dhanapal Avatar asked Nov 27 '25 22:11

Dhanapal


1 Answers

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) where index runs from 0 to length-1 and which internally does ((index+start)%length).

That way, you can apply the binary search without thinking about the actual data layout.

like image 73
Aaron Digulla Avatar answered Dec 02 '25 05:12

Aaron Digulla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!