Binary Search
- Get link
- X
- Other Apps
Sample Input 1:
5
2
1 2 3 4 5
Sample Output 1:
1
import java.util.Scanner; public class BinarySearch { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int x=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int ab=binarySearch(a, x); System.out.println(ab); } public static int binarySearch(int[] arr, int x) { int l=0; int e=arr.length-1; while(l<=e) { int m=(l+e)/2; if(arr[m]==x) { return m; } else if(arr[m]>x) { e=m-1; } else { l=m+1; } } return -1; } }
- Get link
- X
- Other Apps
Comments
Post a Comment