Skip to content

Commit b8d8992

Browse files
author
Vinay Patel
committed
2 parents 24af30c + 5b01531 commit b8d8992

File tree

2 files changed

+1427
-0
lines changed

2 files changed

+1427
-0
lines changed

Binary Search Tree/BS.java

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

0 commit comments

Comments
 (0)