#include <bits/stdc++.h>
using namespace std;
// iterative binary search
int binary_search_iterative(vector<string> arr, string key)
{
int l = 0, r = arr.size();
while (l <= r)
{
int mid = l + (r - l) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
// recursive binary search
int binary_search_recursive(vector<string> arr, string key, int l, int r)
{
if (l > r)
return -1;
int mid = l + (r - l) / 2;
if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
return binary_search_recursive(arr, key, mid + 1, r);
return binary_search_recursive(arr, key, l, mid - 1);
}
// to print
void print(vector<string> &a)
{
for (auto it : a)
cout << it << " ";
cout << endl;
}
int main()
{
cout << "Enter size of the Input words : ";
int n;
cin >> n;
vector<string> arr(n);
cout << "Enter the words\n";
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
cout << "Enter searching key\n";
// key there
string key;
cin >> key;
cout << "Sorting the input list to ensure binary search works\n";
sort(arr.begin(), arr.end());
cout << "\nPrinting the sorted word list\n";
print(arr);
int index = binary_search_iterative(arr, key);
if (index == -1)
cout << key << " not found\n";
else
cout << key << " found at index(0 based): " << index << endl;
index = binary_search_recursive(arr, key, 0, n - 1);
if (index == -1)
cout << key << " not found\n";
else
cout << key << " found at index(0 based): " << index << endl;
return 0;
}
Output
Enter size of the Input words : 5
Enter the words
cat
dog
panda
horse
snake
Enter searching key
panda
Sorting the input list to ensure binary search works
Printing the sorted word list
cat dog horse panda snake
panda found at index(0 based): 3 /// iterative
panda found at index(0 based): 3 /// recursive
0 Comments