Last Updated: 06 October, 2024 5 Mins
A search is the process of finding a specific element in a list. In this tutorial, we are going to talk about how to search for a specific element in a list using a binary search algorithm in Java.
The binary search algorithm is a technique for searching a specific element within a sorted list of elements. It uses the divide-and-conquer approach to rapidly find the specific element by repeatedly dividing the search space in half.
If the specific element is less than the middle element, it can't be in the right half of the data structure, so discard it and focus on the left half. Conversely, if the target element is greater, discard the left half and focus on the right half and continue this process of dividing and searching until we either find the target element or reach an empty sub-array, indicating the element is not present.
The binary search algorithm is powerful and efficient. It is achieving a time complexity of O(log n), where n is the total number of elements in the list. It is significantly faster than linear search (O(n)).
There are the following ways to implement binary search in Java:
Output
Element 40 is present at the index 3
Element 250 is not present in array
Output
Element 40 is present at the index 3
Element 250 is not present in array
Output
The key: 60 found at the index = 5
The key: 100 is not found in the array
Output
The key: 30 found at the index = 2
The key: 90 is not found in the list
That's all, guys. I hope this article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com