Sign in to follow this  

Binary Search in an STL List

This topic is 4664 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
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
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

This topic is 4664 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this