You are on page 1of 1

Name : Anagha S

Class : CS3C Date: 02/12/2023


Roll No : 18

5c. BINARY SEARCH


PROGRAM
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
int[]a=new int[20];
System.out.println("Enter the size of array");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
System.out.println("Enter "+n+" sorted elements");
for(int i=0;i<n;i++)
a[i]=s.nextInt();
System.out.println("Enter the element to be searched");
int sk=s.nextInt();
int l=0,h = n-1;
while(l<h){
int mid=(l+h)/2;
if(a[mid]==sk) {
System.out.println(sk + " found at location " + (mid + 1));
break;
}
else if(a[mid]<sk)
l=mid+1;
else
h=mid-1;

}
}
}
OUTPUT
Enter the size of array
5
Enter 5 sorted elements
20 30 40 50 60
Enter the element to be searched
50
50 found at location 4

You might also like