We use cookies to improve your experience. If you continue to use our site, we'll assume that you're happy with it. :)

Binary Search Program in Java

Binary Search is an algorithm which is used to find something from arrays or list. We use this method instead of linear search for faster results.

Binary search is the search technique which works efficiently on the sorted lists. Hence, in order to search an element into some list by using binary search technique, we must ensure that the list is sorted.

Binary search follows divide and conquer approach in which, the list is divided into two halves and the item is compared with the middle element of the list. If the match is found then, the location of middle element is returned otherwise, we search into either of the halves depending upon the result produced through the match.

Source Code:

class BinarySearch {

  boolean binarySearchAlgo(int [] arr, int start, int end, int target){
      int midIndex = ((start + end)/2);

      if (start > end) return false;
      if (arr[midIndex] == target) return true;
      if (arr[midIndex] > target) return binarySearchAlgo(arr, start, midIndex-1, target);
      else
          return binarySearchAlgo(arr, midIndex+1, end, target);

  }


  public static void main(String[] args) {

      int[] arr = {2,4,6,7,9,11,34,45,73,91};

      int start = 0;
      int end = arr.length-1;
      int target = 73;
      BinarySearch obj = new BinarySearch();
      System.out.println(obj.binarySearchAlgo(arr, start, end, target));
  }
}

Output: 

 true

Post a Comment