Skip to content

Commit 66822bd

Browse files
add BinarySearch.java
1 parent 4e7740d commit 66822bd

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Diff for: src/BinarySearch.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class BinarySearch {
2+
3+
public static int binarySearch(int arr[], int low, int high, int key) {
4+
int mid = (low + high) / 2;
5+
6+
while (low <= high) {
7+
if (arr[mid] < key) {
8+
low = mid + 1;
9+
} else if (arr[mid] == key) {
10+
return mid;
11+
} else {
12+
high = mid - 1;
13+
}
14+
mid = (low + high) / 2;
15+
}
16+
if (low > high) {
17+
return -1;
18+
}
19+
return -1;
20+
}
21+
22+
public static void main(String[] args) {
23+
int intArray[] = {7, 8, 9};
24+
25+
int key = 5;
26+
27+
if (binarySearch(intArray, 0, 5, key) != -1) {
28+
29+
System.out.print("searching `");
30+
System.out.print(key);
31+
System.out.print("` in the array... it's at index ");
32+
System.out.println(binarySearch(intArray, 0, 5, key));
33+
34+
35+
} else {
36+
37+
System.out.println("index not found");
38+
39+
}
40+
}
41+
42+
}

0 commit comments

Comments
 (0)