Skip to content

Commit 9345c60

Browse files
authored
Merge pull request #466 from Jagannath8/binary_search
Binary search (Java) added
2 parents 2edda37 + a735e45 commit 9345c60

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// Binary search is used to search a key element from multiple elements in an array.
2+
3+
class BinarySearch{
4+
public static void binarySearch(int arr[], int first, int last, int key){
5+
int mid = (first+last)/2;
6+
while (first <= last){
7+
8+
if (arr[mid]<key){
9+
first = mid+1;
10+
}
11+
12+
else if(arr[mid]==key){
13+
System.out.println("Element found at index: "+ mid);
14+
break;
15+
}
16+
17+
else{
18+
last = mid-1;
19+
}
20+
21+
mid = (first+last)/2;
22+
}
23+
24+
if(first > last){
25+
System.out.println("Element not found");
26+
}
27+
}
28+
29+
30+
public static void main (String[] args) {
31+
int arr[] = {10,20,30,40,50};
32+
int key=40;
33+
int last = arr.length-1;
34+
binarySearch(arr, 0, last, key);
35+
}
36+
37+
}
38+
39+
// Time Complexity = O(logn)
40+
// Space Complexity = O(1)

0 commit comments

Comments
 (0)