Skip to content

Commit 85d725c

Browse files
authored
Merge pull request #439 from Divyanshu6566/patch-2
Java code for binary search
2 parents bdbf1fb + b91fd07 commit 85d725c

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Binary_search.java

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class Binary_search {
2+
public static void main(String[] args) {
3+
int[] arr = {-12, -10, 2, 3, 4, 5, 7, 9, 10, 23, 45, 67};
4+
int target = 67;
5+
System.out.println(binarySearch(arr,target));
6+
}
7+
static int binarySearch(int[] arr, int target){
8+
int start = 0;
9+
int end = arr.length-1;
10+
11+
while(start <= end){
12+
13+
int mid = start + (end - start)/2;
14+
15+
if( arr[mid] > target){
16+
end = mid-1;
17+
}
18+
else if(arr[mid] < target){
19+
start = mid+1;
20+
21+
}else{
22+
return mid;
23+
}
24+
25+
}
26+
return -1;
27+
}
28+
}

0 commit comments

Comments
 (0)