Question: Modify the c++ binarySearch function presented below so that it searches an array of strings instead of an array of integers (use any set of
Modify the c++ binarySearch function presented below so that it searches an array of strings instead of an array of integers (use any set of strings such as city names). Test the function with a driver program. (Note: the array must be sorted before the binary search will work).
#include
using namespace std; const int n=5; void Initialize(int a[]);
void BubbleSort(int a[]);
void Display(int a[]);
int BinarySearch(int a[],int value); int main()
{
int a[n], value, index;
Initialize(a);
BubbleSort(a);
Display(a);
cout<<"What element are you looking for? ";
cin>>value;
index=BinarySearch(a,value);
if(index==-1)
cout<<"The element is not in the array."< else cout< return 0; } void Initialize(int a[]) { int i; for(i=0;i { cout<<"a["< cin>>a[i]; } } void BubbleSort(int a[]) { int i, temp; bool swapped=true; while(swapped) { swapped=false; for(i=0;i { if(a[i]>a[i+1]) { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; swapped=true; } } } } void Display(int a[]) { int i; cout<<"The sorted list: "< for(i=0;i cout<<"a["< } int BinarySearch(int a[],int value) { int low, high, mid; low=0; high=n-1; while(low<=high) { mid=(low+high)/2; if(a[mid]==value) return mid; if(a[mid]>value) high=mid-1; else low=mid+1; } return -1; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
