Search code examples
c++performancesearch

At what point does binary search become more efficient than sequential search?


I've been learning a lot about algorithms lately, and the binary searched is hailed for its efficiency in finding an item in large amounts of sorted data. But what if the data is not sorted to begin with? at what points does a binary search provide an efficiency boost against sequential search, with binary search having to sort the given array first off THEN search. I'm interested in seeing at what points binary search passes over sequential search, if anyone has tested this before i would love to see some results.

Given an array foo[BUFF] with 14 elements

1 3 6 3 1 87 56 -2 4 61 4 9 81 7

I would assume a sequential sort would be more efficient to find a given number, let's say... 3, because binary search would need to first sort the array THEN search for the number 3. BUT:

Given an array bar[BUFF] with one thousand elements held

1 2 4 9 -2 3 8 9 4 12 4 56 //continued

A call to sort then binary search should in theory be more efficiently if i am not mistaken.


Solution

  • In an unsorted array where no information is known, you are going to have to do linear time search.

    Linear time search checks each element once, so it's complexity is O(n). Comparing that to sorting. Sorting algorithms which must check each element more than once and have a complexity of O(n * log n). So to even get it sorted is slower than a sequential search. Even though binary search is O(log n) it's pretty useless when you just have arbitrarily ordered data.

    If your going to search for stuff multiple times though, consider sorting first as it'll increase your efficiency in the long run.