Binary Search using Java

 import java.util.Scanner;

class BinarySearch

{

public static void main(String[] args)

{

int low,high,mid,i,n;

 Scanner sc = new Scanner(System.in);

System.out.println("Enter the size of array");

n= sc.nextInt();

int [] arr = new int[n];

System.out.println("Enter the elements");

for(i=0;i<n;i++)

{

arr[i]=sc.nextInt();

}

System.out.println("Enter the elements you want to search");

int e = sc.nextInt();

low=0;

high=n-1;

while(low<=high)

{

mid=(low+high)/2;

if(arr[mid]==e)

{

System.out.println("Element found at index " + mid  );

break;

}

else if(arr[mid]<e)

{

low = mid+1;

}

else

{

high = mid-1;

}

}


if(low>high)

System.out.println( e + " Not found ");

}

}


Input :-

Enter the size of array : - 5

Enter the elements :- 1,2,3,4,5

Enter the elements you want to search : - 5

Output :-

Element found at index  :- 4


Enter the size of array : - 5

Enter the elements :- 1,2,3,4,5

Enter the elements you want to search : - 8

Output :-

Not found


Comments

Post a Comment

Popular posts from this blog

LCM and GCD/HCF code

Calculator Using Switch Case in Java