Search code examples
algorithmsortingsearchbinary-search

Binary search vs simple search


As per algorithm books, binary search's performance is O(log n) while for simple search it is O(n).

But why don't we also take into account the time spend in sorting which is a prerequisite for binary search?


Solution

  • In short: because usually the constructing that list is only done once, whereas searching (and updating) is done multiple times.

    Constructing a sorted list requires indeed O(n log n). The point of using binary search is that once the collection is sorted, we can perform multiple queries on that list, each with O(log n).

    Furthermore if you use a binary search tree for example, you can perform insertion, and removal of elements in O(log n) as well, so updating the collection can be cheap as well (given you use an effective data structure for that).

    In a database for example one frequently uses indexes to perform fast lookups. Usually the number of reads is large compared to the number of updates. Updating a single element requires O(log n), so creating the index on existing data is indeed expensive, but this is not very common compared to searching and updating a B-tree datastructure [wiki].