Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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

‎src/BinarySearch.java‎

Lines changed: 42 additions & 0 deletions
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)

AltStyle によって変換されたページ (->オリジナル) /