• API
• FAQ
• Tools
• Archive
SHARE
TWEET # BinarySearch a guest Dec 7th, 2019 110 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. // C++ program to implement recursive Binary Search
2. #include <iostream>
3.
4. using namespace std;
5.
6.
7. // A recursive binary search function. It returns
8. // location of x in given array arr[l..r] is present,
9. // otherwise -1
10.
11. int binarySearch(int arr[], int l, int r, int x)
12. {
13.
14.     if (r >= l) {
15.
16.         int mid = l + (r - l) / 2;
17.
18.
19.
20.         // If the element is present at the middle
21.
22.         // itself
23.
24.         if (arr[mid] == x)
25.
26.             return mid;
27.
28.
29.
30.         // If element is smaller than mid, then
31.
32.         // it can only be present in left subarray
33.
34.         if (arr[mid] > x)
35.
36.             return binarySearch(arr, l, mid - 1, x);
37.
38.
39.
40.         // Else the element can only be present
41.
42.         // in right subarray
43.
44.         return binarySearch(arr, mid + 1, r, x);
45.
46.     }
47.
48.
49.
50.     // We reach here when element is not
51.
52.     // present in array
53.
54.     return -1;
55. }
56.
57.
58.
59. int main(void)
60. {
61.   char choice;
62.   char string;
63.
64.     int arr[] = { 5, 10, 15, 20 ,25, 50, 65, 70, 90, 100 };
65.
66.     int x;
67.          cout << "input your choice" << endl << endl;
68.          cin >> x;
69.
70.     int n = sizeof(arr) / sizeof(arr);
71.
72.     int result = binarySearch(arr, 0, n - 1, x);
73.
74.     (result == -1) ? cout << "Element is not present in array"
75.
76.                    : cout << "Element is present at index " << result;
77.
78.     return 0;
79. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top