Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

how to implement Binary Search in Java ?.

package com.hubberspot.binarysearch.example;

import java.util.Scanner;

public class BinarySearch {
  public static void main(String[] args){       
    int[] numbers = {3, 4, 5, 6, 7, 2, -3, 4, 16, 14};
    sort(numbers);
        
    Scanner scanner = new Scanner(System.in);    
    System.out.println("Enter the number you want to "
            + "search from array : ");
    
    int key = scanner.nextInt();
        
    boolean position = binarySearch(numbers,key);
    
    if(position == true)
      System.out.println("Array contain the element to "
              + "be searched");
    else
      System.out.println("Array does not contain the element"
              + " to be searched");
    }
    
  public static void sort(int[] list) {
    boolean nextPass = true;
    
    for (int k = 1; k < list.length && nextPass; k++) {
      nextPass = false;
      for (int i = 0; i < list.length - k; i++) {
        if (list[i] > list[i + 1]) {
      
          int temp = list[i];
          list[i] = list[i + 1];
          list[i + 1] = temp;
          
          nextPass = true; 
        }
      }
    }
  }  
    
  public static boolean binarySearch(int[] list, int key) {
    int low = 0;
    int high = list.length - 1;

    while (high >= low) {
      int mid = (low + high) / 2;
      if (key < list[mid])
        high = mid - 1;
      else if (key == list[mid])
        return true;
      else
        low = mid + 1;
    }

    return false; 
  }
}

Output of the program




Video tutorial to demonstrate how to implement Binary Search in Java.








 
© 2021 Learn Java by Examples Template by Hubberspot