Linear search and Binary search programs

Linear Search: int[] ar = {10,45,67,100} int key = 67; for(int i=0;i

Feb 24, 2025 - 19:01
 0
Linear search and Binary search programs

Linear Search:

int[] ar = {10,45,67,100}       
int key = 67;
for(int i=0;i

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

output:
key is present :2