import java.util.Scanner;
public class hw2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter no of elements in the array:");
int n = sc.nextInt();
System.out.println("enter 5 no of elements in ascending order::");
int a[]= new int[n];
for(int i=0;i<a.length;i++) {
a[i]= sc.nextInt();
}
System.out.println("Enter the elments to search:");
int s= sc.nextInt();
int key=s;
int first=a[0];
int last = a[n-1];
int res=binser(a,s,first,last);
if(res!=-1) {
System.out.println("the "+key+" is present at index "+res);
}
else {
System.out.println("the "+key+" is not present in the array");
}
}
public static int binser(int a[],int s,int start,int end) {
if(end>=start && start<=a.length-1) {
int mid = start+(end-start)/2;
if(a[mid]==s) {
return mid;
}
if(a[mid]>s) {
return binser(a,s,start,mid-1);
}
return binser(a,s,mid+1,end);
}
return -1;
}
}
OUTPUT:
enter no of elements in the array:
5
enter 5 no of elements in ascending order::
11
22
33
44
55
Enter the elments to search:
33
the 33 is not present in the array