Skip to content

Commit 75438d1

Browse files
authored
Create Binary Search 1
1 parent f3b97bb commit 75438d1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

Binary Search 1

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
}

0 commit comments

Comments
 (0)