Best possible way to search for a given value among N unsorted numbers

时间:2016-10-20 18:46:31

标签: c++ c data-structures

One of my friend has been asked with a question in an interview:

The best possible way to search for a given value among N unsorted numbers in a array.

3 个答案:

答案 0 :(得分:3)

If the array is unsorted, you need to perform a linear scan of the list. This examines (worst case) every element in the array. Such a search is O(n).

Sorting won't help here, since the best sorts run in O(n log n).

答案 1 :(得分:0)

If it was sorted I'd say std::binary_search, but for unsorted, just go with std::find (unless the container you use has a member find; if it does, then use that as it is probably faster).

答案 2 :(得分:0)

It depends: -if you just want to search a single value, the answer given by bush is enough.

-if you know what you want to perform repeated "query", it could be better to perform before some kind of preprocessing,in order to find fastly these value.If you want to know only if a value is contained in the array, you can use structures like hashset,bloom filter,etc.. In other cases,you would like to know also position of items inside the array. In this scenario,you can consider to use an hashmap