DEV Community

Saravanan
Saravanan

Posted on

Linear search and Binary search programs

Linear Search:

int[] ar = {10,45,67,100}       
int key = 67;
for(int i=0;i<ar.length;i++)
{
 if(ar[i]==key)
 System.out.println("key is presented :"+i);
}
Enter fullscreen mode Exit fullscreen mode

output:
key is presented :2

Binary Search:


int[] ar = {10,16,18,21,27,37, 45, 98,100};
int key = 18;
int max_idx = ar.length-1;
int min_idx=0;
while(min_idx<=max_idx)
{
    int mid_idx=(min_idx+max_idx)/2;        
    if(ar[mid_idx]==key)            

    {
        System.out.println("key is present :" + mid_idx);
        break;
    }
    else if(key>ar[mid_idx])    
    {
        min_idx= mid_idx+1;
    }
    else if(key<ar[mid_idx]) 
    {
        max_idx= mid_idx-1;     
    }


}
Enter fullscreen mode Exit fullscreen mode

output:
key is present :2

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay