Skip to content

Commit 76d1206

Browse files
authored
Create Binary_Search.java
Fixes #371 Hope this solves the issue. Please merge it if you like it !!!
1 parent 4486fd8 commit 76d1206

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Binary_Search.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
public class Main{
2+
3+
public static int binarySearch(int array[], int left, int right, int item){
4+
5+
if (right >= left){
6+
7+
// calculation of new mid
8+
int mid = left + (right - left)/2;
9+
10+
// returns position where found
11+
if (array[mid] == item)
12+
return mid+1;
13+
14+
// goes to recursive calls in left half
15+
if (array[mid] > item)
16+
return binarySearch(array, left, mid-1, item);
17+
18+
// goes to recursive calls in right half
19+
else
20+
return binarySearch(array, mid+1, right, item);
21+
}
22+
// if element is not found we return -1
23+
else
24+
return -1;
25+
}
26+
public static void main(String args[]){
27+
28+
int[ ] array = {10, 20, 30, 40, 50, 60, 70, 80};
29+
int item = 70;
30+
int size = array.length;
31+
32+
int position = binarySearch(array, 0, size-1, item);
33+
34+
if(position == -1)
35+
System.out.println("Element not found");
36+
else
37+
System.out.println("The value " + item + " found at position: " + position);
38+
39+
}
40+
}

0 commit comments

Comments
 (0)