Course contentsShow
← Java
Lesson 270 of 2,8706. ArraysFree lesson

Arrays.binarySearch: Efficient Element Lookup

Searching for elements in sorted arrays with O(log n) complexity using binarySearch.

Arrays.binarySearch: Efficient Element Lookup

What You'll Learn

You'll discover how to search for elements in sorted arrays lightning-fast using Arrays.binarySearch, which finds items in O(log n) time instead of checking every element.

Why Binary Search Is So Fast

Imagine looking up a word in a dictionary. You don't start at page 1 and flip through every page—you open somewhere in the middle, see if your word comes before or after, then eliminate half the remaining pages. You repeat this process, halving your search space each time.

That's exactly what Arrays.binarySearch does with sorted arrays. Instead of checking all elements one by one (O(n) time), it repeatedly divides the search space in half, achieving O(log n) complexity. For a 1,000-element array, this means ~10 comparisons instead of potentially 1,000!

Using Arrays.binarySearch

The method requires a sorted array:

int[] numbers = {2, 5, 8, 12, 16, 23, 38, 45, 56, 67};

int index = Arrays.binarySearch(numbers, 23);
// Returns: 5 (the index where 23 is found)

int notFound = Arrays.binarySearch(numbers, 20);
// Returns: negative value (element not present)

When the element is not found, binarySearch returns a negative value: -(insertion point) - 1. This tells you where the element would go to maintain sorted order.

int result = Arrays.binarySearch(numbers, 20);
// Returns: -6 
// Insertion point would be index 5 (between 16 and 23)

You can also search within a range:

int index = Arrays.binarySearch(numbers, 2, 7, 16);
// Searches from index 2 to 6 (exclusive end)

Critical Requirement

The array MUST be sorted before calling binarySearch. If it's not sorted, results are undefined. Use Arrays.sort first if needed.

Key Takeaway: Arrays.binarySearch finds elements in sorted arrays with O(log n) efficiency by repeatedly halving the search space, but only works correctly on sorted arrays.