- for the size of array
- for array
- Number to search in array
In this program loop will go upto the value of n-1 or i<n then m is compared to value of arr[i] if the value is in array then it return the value of i else -1;
5
11 12 13 14 15
14
Sample Output 1
3
Sample Input 2
3
1 4 6
4
Sample Output 2
1
Program
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int [n];
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}
int m=sc.nextInt();
System.out.println(search(arr, m));
}
public static int search(int[] arr,int m) {
int lo=0;
int hi=arr.length-1;
while(lo<=hi)
{
int mid =(lo+hi)/2;
if(arr [mid]==m)
{
return mid;
}
else if(arr[mid]>m)
{
hi=mid-1;
}
else
{
lo=mid+1;
}
}
return -1;
}
}