Skip to content

Commit ada496a

Browse files
authored
Create Binary Search Algorithm.
1 parent d4f6b3d commit ada496a

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Binary Search Algorithm.

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package test;
2+
public class BinarySearch {
3+
// Java implementation of recursive Binary Search
4+
// Returns index of x if it is present in arr[l..
5+
// r], else return -1
6+
int binarySearch(int arr[], int l, int r, int x)
7+
{
8+
if (r >= l) {
9+
int mid = l + (r - l) / 2;
10+
// If the element is present at the
11+
// middle itself
12+
if (arr[mid] == x)
13+
return mid;
14+
// If element is smaller than mid, then
15+
// it can only be present in left subarray
16+
if (arr[mid] >x)
17+
return binarySearch(arr, l, mid - 1, x);
18+
// Else the element can only be present
19+
// in right subarray
20+
return binarySearch(arr, mid + 1, r, x);
21+
}
22+
// We reach here when element is not present
23+
// in array
24+
return -1;
25+
}
26+
public static void main(String args[])
27+
{
28+
BinarySearch ob = new BinarySearch();
29+
int arr[] = { 2, 3, 4, 10, 40 };
30+
int n = arr.length;
31+
int x = 40;
32+
int result = ob.binarySearch(arr, 0, n - 1, x);
33+
if (result == -1)
34+
System.out.println("Element not present");
35+
else
36+
System.out.println("Element found at index " + result);
37+
}
38+
}

0 commit comments

Comments
 (0)