10000 Added Binary Search Algorithm · sonwanigaurav/Java-Algorithms@44cc540 · GitHub
[go: up one dir, main page]

Skip to content

Commit 44cc540

Browse files
Added Binary Search Algorithm
1 parent 2122ac1 commit 44cc540

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

.vscode/launch.json

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"configurations": [
3+
{
4+
"type": "java",
5+
"name": "CodeLens (Launch) - BinarySearch",
6+
"request": "launch",
7+
"mainClass": "BinarySearch",
8+
"projectName": "Java-Algorithms_881fe886"
9+
}
10+
]
11+
}

Searching/BinarySearch.java

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

0 commit comments

Comments
 (0)
0