In this program, you'll learn to implement Binary Search in Java. Binary Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
Algorithm :
- Algorithm is quite simple. It can be done either recursively or iteratively:
- get the middle element;
- if the middle element equals to the searched value, the algorithm stops; otherwise, two cases are possible:
- searched value is less, than the middle element.
- In this case, go to the step 1 for the part of the array, before middle element. searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element.
Binary Search
When you run the program, the output will be:
Search for element 10 is found at 4