Skip to content

Commit 8ab4deb

Browse files
authored
Update BinarySearch.java
binary search explained in a better way using functions
1 parent d1ea04d commit 8ab4deb

File tree

1 file changed

+45
-17
lines changed

1 file changed

+45
-17
lines changed

core-java/basics/BinarySearch.java

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,47 @@
1-
package basics;
2-
import java.util.Arrays;
3-
4-
public class BinarySearch {
5-
6-
public static void main(String[] args) {
7-
8-
int arr[] = {10, 20, 15, 22, 35};
9-
Arrays.sort(arr);
10-
11-
int key = 35;
12-
int res = Arrays.binarySearch(arr, key);
13-
if(res >= 0){
14-
System.out.println(key + " found at index = "+ res);
15-
} else {
16-
System.out.println(key + " not found");
17-
}
1+
// Java implementation of iterative Binary Search
2+
3+
import java.io.*;
4+
5+
class BinarySearch {
6+
7+
// Returns index of x if it is present in arr[].
8+
int binarySearch(int arr[], int x)
9+
{
10+
int l = 0, r = arr.length - 1;
11+
while (l <= r) {
12+
int m = l + (r - l) / 2;
13+
14+
// Check if x is present at mid
15+
if (arr[m] == x)
16+
return m;
17+
18+
// If x greater, ignore left half
19+
if (arr[m] < x)
20+
l = m + 1;
21+
22+
// If x is smaller, ignore right half
23+
else
24+
r = m - 1;
25+
}
26+
27+
// If we reach here, then element was
28+
// not present
29+
return -1;
30+
}
31+
32+
// Driver code
33+
public static void main(String args[])
34+
{
35+
BinarySearch ob = new BinarySearch();
36+
int arr[] = { 2, 3, 4, 10, 40 };
37+
int n = arr.length;
38+
int x = 10;
39+
int result = ob.binarySearch(arr, x);
40+
if (result == -1)
41+
System.out.println(
42+
"Element is not present in array");
43+
else
44+
System.out.println("Element is present at "
45+
+ "index " + result);
1846
}
1947
}

0 commit comments

Comments
 (0)