is there an algorithm that is faster than binary search, for searching in sorted values of array?
in my case, I have a sorted values (could be any type values) in an
First of all, measure before doing optimization.
Do you really need to optimize that search?
If so, then secondly, think about algorithmic complexity first. E.g. can you use a tree (like a std::map
, say) instead of an array? If so then it depends on the relative frequency of insertions/deletions versus searches, but the premise of having a sorted array at hand indicates that searches are frequent compared to data set changes, so that it would make sense to do some little additional work for insertions/deletions, making each search much faster -- namely logarithmic time.
If you find that indeed the search times are a bottleneck that needs addressing, and no, no change of data representation is possible, and the list is short, then a linear search will generally be faster because it does less work per comparision.
Otherwise, if the list is longer, and no particular distribution of values is known or assumed, and the values can't be treated as numerical, and memory consumption should be constant (ruling out constructing a hash table, say), then binary search produces 1 bit of information per comparision and is probably the best you can do for the first search.
Cheers & hth.