Binary Search Source Code in Java

In this source code example, we will write a Java program to demonstrate how to implement the Binary Search algorithm in Java.

Binary search is an efficient search algorithm that works on sorted lists. It works by repeatedly dividing the list in half and checking if the target element is greater than, less than, or equal to the element at the midpoint of the list. If the target element is less than the midpoint element, the search continues in the left half of the list. If the target element is greater than the midpoint element, the search continues in the right half of the list. This process is repeated until the target element is found or it is clear that the element is not on the list.

Binary Search Source Code in Java

public class BinarySearch {

   public int binarySearch(int[] nums, int key) {
      int low = 0;
      int high = nums.length - 1;

      while (low <= high) {
         int mid = (high + low) / 2;

         if (nums[mid] == key) {
            return mid;
         }
         if (key < nums[mid]) {
            high = mid - 1;
         } else {
            low = mid + 1;
         }
      }
      return -1;
   }

   public static void main(String[] args) {
      BinarySearch bs = new BinarySearch();
      int[] nums = { 1, 10, 20, 47, 59, 65, 75, 88, 99 };
      System.out.println(bs.binarySearch(nums, 65));
   }
}

Output:

5

Binary search has a time complexity of O(log n), where n is the number of elements in the list. This means that the search time increases logarithmically with the size of the list, making it much more efficient than a linear search for large lists. However, binary search can only be used on sorted lists, so the list must be sorted before the search can be performed.


Comments