Jacob_Thomas

Binary Search

Jan 28th, 2021
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.19 KB | None | 0 0
  1. import java.util.*;
  2. class BinarySearch{
  3.     public static void main(String args[]){
  4.         int arr[], key, len;
  5.         Scanner sc = new Scanner(System.in);
  6.         System.out.println("Enter the size of array");
  7.         len = sc.nextInt();
  8.         arr = new int[len];
  9.         System.out.println("Enter the array");
  10.         for(int x = 0; x<len; x++){
  11.             arr[x] = sc.nextInt();
  12.         }
  13.         key = sc.nextInt();
  14.         Arrays.sort(arr);
  15.         boolean result = BinarySearch.Search(0, len-1, arr, key);
  16.         if(result == true)
  17.         System.out.println("Key is present in array");
  18.         else
  19.         System.out.println("Key is not present in the array");
  20.     }
  21.    
  22.     static boolean Search(int start, int end, int arr[],int key){
  23.         int mid = (start+end)/2;
  24.         if(arr[start]!=key && arr[end]!=key && arr[mid]!=key){
  25.             if((start+1) == end){
  26.                 return false;
  27.             }
  28.             if(arr[mid]>key){
  29.                 return Search(start, mid-1, arr, key);
  30.             }
  31.             else{
  32.                 return Search(mid+1, end, arr, key);
  33.             }
  34.         }
  35.         else{
  36.             return true;
  37.         }
  38.     }
  39. }
  40.  
Advertisement
Add Comment
Please, Sign In to add comment