Video in progress

What is the difference between linear search and binary search, and what condition does binary search need?

Linear search checks the elements one by one: O(n), and it works on any array. Binary search halves the range at every step: O(log n), but the array must be sorted beforehand.

📖 Answer

In an array of a million elements, linear search takes a million steps in the worst case, while binary search takes about 20.

But binary search has a condition: the data must be sorted. On an unsorted array, Arrays.binarySearch doesn't throw an error, it just returns a wrong answer. That's a very sneaky bug.

When to use which:

  • you search once and the array is unsorted: linear, because sorting at O(n log n) costs more than a single search;
  • you search many times: sort once, then use binary search;
  • you add and search often: HashSet/HashMap or TreeMap is better.

When Arrays.binarySearch doesn't find the element, it returns a negative number: -(insertion point) - 1. If you know that, you also know where to insert the element without breaking the order.