Wednesday, July 1, 2020

Binary Search

Binary Search

Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.

PROGRAM:

import java.util.*;
public class binary_search {
    
    
        static int search(int x[],int s,int m)
        {
            
       int  low=0;
        int high=m-1;
        while(low<high)
        {
            int mid=(low+high/2);
            if(s==x[mid])
            {
                return mid;
            }
            else if(s<x[mid])
            {
                high=mid-1;
            }
            else
            {
                low=mid+1;
            }
        }
         return -1;   
        }
        
        
        public static void main(String args[])
    {
        int n,key,low,high,mid;
        Scanner sc=new Scanner(System.in);
        int a[]=new int[20];
        System.out.println("Enter n");
         n=sc.nextInt();
        System.out.println("Enter numbers");
        for (int i=0;i<n;i++)
        {
             a[i]=sc.nextInt();
            
        }
        
        System.out.println("Enter key to be searched");
        key=sc.nextInt();
        System.out.println("" +search(a,key,n) );
        
        
    }
}
    
OUTPUT:
Enter n
5
Enter numbers
1 2 3 4 5
Enter key to be searched
3
2


No comments:

Post a Comment