Jump to content
  • Advertisement
Sign in to follow this  
Chrysaor

Binary Search in an STL List

This topic is 4881 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I'm wondering if its possible to do a binary search using an STL List (you know, search the middle element, compare, if its bigger search the lower half, if hits lower, search the higher half, and repeat). My list is all sorted (hence why i used List instead of a vector). I've searched the MSDN but i cant seem to find anything. Any help would be greatly appreciated.

Share this post


Link to post
Share on other sites
Advertisement
Binary search relies heavily on random access which a linked list can't provide.
It can still be used to cut down on the number of comparisons. But that won't gain you anything unless they're VERY expensive compared to normal traversation.

Share this post


Link to post
Share on other sites
As doynax said, a std::list can't do random access, only sequential access, which is a bad thing for a binary search. You'll need to use a container that supports random access like vector or deque. Alternatively, use a container like std::map, which will handle the searching for you.

Share this post


Link to post
Share on other sites
As doynax points out, binary search is efficient only if your container provides random access; binary searching a list would be slower than just iterating the whole thing once! If you want a structure kept sorted and offering O(log N) lookup, you may want some sort of tree.

The easiest thing to do is probably to simply use a std::map (if you have key/value pairs) or std::set (if all you have is values). They provide guaranteed worst-case O(log N) insertion and access time (typically, these ADTs are implemented as red-black trees).

Share this post


Link to post
Share on other sites
You could put the iterators into a vector and then sort using a dereferencing functor. Then you can search.

Share this post


Link to post
Share on other sites
Thanks everybody.

I managed to do something like binary search, didnt notice a bad exec time, but there were a couple of problems. Converted to map, reduced my code by alot, made it simpler, and all works like a charm (so far). So thanks for the quick help everybody!

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!