binarysearch

mail@pastecode.io avatar
unknown
java
2 months ago
941 B
3
Indexable
Never
class Binaryexample
{
    public static void binary(int a[],int left,int right,int search)
    {
       int mid=(left+right)/2;
       while(left<=right)
       {
           if(a[mid]<search)
           {
               left=mid+1;
               
           }
           else if(a[mid]==search)
           {
               System.out.println("the element is found at position"+mid);
               break;
               
           }
           else
           {
               right=mid-1;
           }
           mid=(left+right)/2;
       }
           if(left>right)
           {
               System.out.println("element not found");
           }
       }
        
        
        
        
public static void main(String[] args)
   {
        int a[] = {10,20,30,40,50};  
        int search = 20;  
        int right=a.length-1;  
        binary(a,0,right,search); 
        
    }
}
    

Leave a Comment