Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class BinarySearch{
- public static void main(String args[]){
- int arr[], key, len;
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the size of array");
- len = sc.nextInt();
- arr = new int[len];
- System.out.println("Enter the array");
- for(int x = 0; x<len; x++){
- arr[x] = sc.nextInt();
- }
- key = sc.nextInt();
- Arrays.sort(arr);
- boolean result = BinarySearch.Search(0, len-1, arr, key);
- if(result == true)
- System.out.println("Key is present in array");
- else
- System.out.println("Key is not present in the array");
- }
- static boolean Search(int start, int end, int arr[],int key){
- int mid = (start+end)/2;
- if(arr[start]!=key && arr[end]!=key && arr[mid]!=key){
- if((start+1) == end){
- return false;
- }
- if(arr[mid]>key){
- return Search(start, mid-1, arr, key);
- }
- else{
- return Search(mid+1, end, arr, key);
- }
- }
- else{
- return true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment