File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ //given an array of n element, find a particular element using binary search
2
+
3
+ import java.util.*;
4
+ class Test2{
5
+ static int binarySearch(int key, int arr[],int l,int h){
6
+ int mid=l+(h-l)/2;
7
+ if(h>=l){
8
+ if(arr[mid]==key)
9
+ return mid;
10
+ else if (arr[mid]>key)
11
+ return binarySearch(key, arr,l,mid-1);
12
+ else
13
+ return binarySearch(key, arr,mid+1,h);
14
+ }
15
+ return -1;
16
+ }
17
+
18
+ public static void main(String args[]){
19
+ Scanner sc= new Scanner(System.in);
20
+ System.out.print("Enter the number of elements in the array: ");
21
+ int n=sc.nextInt();
22
+ System.out.print("Enter the elements in the array: ");
23
+ int a[]=new int [n];
24
+ for(int i=0; i<n; i++)
25
+ a[i]=sc.nextInt();
26
+ System.out.print("Enter the elements to search: ");
27
+ int key=sc.nextInt();
28
+ int result=binarySearch(key, a,0,n-1);
29
+ if(result ==-1)
30
+ System.out.print("Element NOT found");
31
+ else
32
+ System.out.print("Element found at index number "+result);
33
+ }
34
+ }
You can’t perform that action at this time.
0 commit comments