Skip to content

Commit 1c39543

Browse files
committed
Merge branch 'ch13-achintya' of https://github.com/code4tomorrow/java into ch13-achintya
2 parents 7c20e93 + 117fcd3 commit 1c39543

File tree

1 file changed

+34
-38
lines changed

1 file changed

+34
-38
lines changed

src/com/codefortomorrow/advanced/chapter13/examples/BinarySearch.java

Lines changed: 34 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,42 @@
11
package com.codefortomorrow.advanced.chapter13.examples;
22

33
public class BinarySearch {
4-
// Java implementation of recursive Binary Search
5-
// Returns index of x if it is present in arr[l..
6-
// r], else return -1
7-
public static int binarySearch(int arr[], int l, int r, int x)
8-
{
9-
if (r >= l) {
10-
int mid = l + (r - l) / 2;
11-
12-
// If the element is present at the
13-
// middle itself
14-
if (arr[mid] == x)
15-
return mid;
16-
17-
// If element is smaller than mid, then
18-
// it can only be present in left subarray
19-
if (arr[mid] > x)
20-
return binarySearch(arr, l, mid - 1, x);
21-
22-
// Else the element can only be present
23-
// in right subarray
24-
return binarySearch(arr, mid + 1, r, x);
25-
}
26-
27-
// We reach here when element is not present
28-
// in array
29-
return -1;
30-
}
314

32-
// Driver method to test above
33-
public static void main(String args[])
34-
{
35-
int arr[] = { 2, 3, 4, 10, 40 };
36-
int n = arr.length;
37-
int x = 10;
38-
int result = binarySearch(arr, 0, n - 1, x);
39-
if (result == -1)
40-
System.out.println("Element not present");
41-
else
42-
System.out.println("Element found at index " + result);
5+
// Java implementation of recursive Binary Search
6+
// Returns index of x if it is present in arr[l..
7+
// r], else return -1
8+
public static int binarySearch(int arr[], int l, int r, int x) {
9+
if (r >= l) {
10+
int mid = l + (r - l) / 2;
11+
12+
// If the element is present at the
13+
// middle itself
14+
if (arr[mid] == x) return mid;
15+
16+
// If element is smaller than mid, then
17+
// it can only be present in left subarray
18+
if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x);
19+
20+
// Else the element can only be present
21+
// in right subarray
22+
return binarySearch(arr, mid + 1, r, x);
4323
}
24+
25+
// We reach here when element is not present
26+
// in array
27+
return -1;
28+
}
29+
30+
// Driver method to test above
31+
public static void main(String args[]) {
32+
int arr[] = { 2, 3, 4, 10, 40 };
33+
int n = arr.length;
34+
int x = 10;
35+
int result = binarySearch(arr, 0, n - 1, x);
36+
if (result == -1) System.out.println(
37+
"Element not present"
38+
); else System.out.println("Element found at index " + result);
39+
}
4440
/* This code is contributed by Rajat Mishra
4541
https://www.geeksforgeeks.org/binary-search/ */
4642

0 commit comments

Comments
 (0)