1
+ // Binary search recursive and iterative
2
+ // Techie delight https://www.techiedelight.com/binary-search/
3
+
4
+ #include < iostream>
5
+ #include < vector>
6
+ #include < cstdlib>
7
+ #include < algorithm>
8
+
9
+ void print (const std::vector<int >& nums)
10
+ {
11
+ for (auto n : nums) {
12
+ std::cout << n << " " ;
13
+ }
14
+ std::cout << " \n " ;
15
+ }
16
+
17
+ std::vector<int > generateRandomNumbers (const int length, const int min, const int max)
18
+ {
19
+ std::vector<int > nums;
20
+ for (int i = 0 ; i < length; ++i) {
21
+ int x = min + (rand () % max - min + 1 );
22
+ nums.push_back (x);
23
+ }
24
+ return nums;
25
+ }
26
+
27
+ int searchIterative (std::vector<int >& nums, const int target)
28
+ {
29
+ int low = 0 ;
30
+ int high = nums.size () - 1 ;
31
+
32
+ while (low <= high) {
33
+ int mid = low + (high - low) / 2 ;
34
+ if (nums[mid] == target) {
35
+ return mid;
36
+ } else if (target < nums[mid]) {
37
+ high = mid - 1 ;
38
+ } else {
39
+ low = mid + 1 ;
40
+ }
41
+ }
42
+
43
+ return -1 ;
44
+ }
45
+
46
+ int searchRecursive (std::vector<int >& nums, const int target, int low, int high)
47
+ {
48
+ if (low > high) {
49
+ return -1 ;
50
+ }
51
+ int mid = low + (high - low) / 2 ;
52
+ if (nums[mid] == target) {
53
+ return mid;
54
+ } else if (target < nums[mid]) {
55
+ return searchRecursive (nums, target, low, mid - 1 );
56
+ } else {
57
+ return searchRecursive (nums, target, mid + 1 , high);
58
+ }
59
+ }
60
+
61
+ int searchRecursive (std::vector<int >& nums, const int target)
62
+ {
63
+ return searchRecursive (nums, target, 0 , nums.size () - 1 );
64
+ }
65
+
66
+ void test (std::vector<int >& nums, const int target)
67
+ {
68
+ std::cout << " Numbers : " ;
69
+ print (nums);
70
+ std::sort (nums.begin (), nums.end (), std::less<int >());
71
+ std::cout << " \n Searching " << target << " using iterative : Found at " << searchIterative (nums, target);
72
+ std::cout << " \n Searching " << target << " using recursive : Found at " << searchRecursive (nums, target);
73
+ std::cout << " \n Searching " << target << " using STL : Found? " << std::boolalpha
74
+ << std::binary_search (nums.begin (), nums.end (), target);
75
+ std::cout << " \n " ;
76
+ }
77
+
78
+ int main ()
79
+ {
80
+ std::vector<int > nums = generateRandomNumbers (50 , 1 , 50 );
81
+ test (nums, 5 );
82
+
83
+ return 0 ;
84
+ }
0 commit comments