Binary Search (Recursive and Iterative) in Java

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 :

  1. Algorithm is quite simple. It can be done either recursively or iteratively:
  2. get the middle element;
  3. if the middle element equals to the searched value, the algorithm stops; otherwise, two cases are possible:
  4. searched value is less, than the middle element.
  5. 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

أحدث أقدم