|
1 | 1 | package com.codefortomorrow.advanced.chapter13.examples; |
2 | 2 |
|
3 | 3 | 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 | | - } |
31 | 4 |
|
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); |
43 | 23 | } |
| 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 | + } |
44 | 40 | /* This code is contributed by Rajat Mishra |
45 | 41 | https://www.geeksforgeeks.org/binary-search/ */ |
46 | 42 |
|
|
0 commit comments