#include <iostream> using namespace std; int binarySearch(const int list[], int
ID: 3618397 • Letter: #
Question
#include <iostream>
using namespace std;
int binarySearch(const int list[], int length,const int &item);
int i=0;
int main()
{
int arr[10],size=10;
int x;
cout<<"Please enter the desirednumber"<<endl;
cin>>x;
cout<<"Please enter a sorted list of10 numbers"<<endl;
while(i<10)
{
cin>>arr[i];
i++;
}
if(binarySearch(arr,size,x)==-1)
cout<<"Number is not in thelist"<<endl;
else
cout<<"The index of the desired numberis "<<binarySearch(arr,size,x)<<endl;
return 0;
}
int binarySearch(const int list[],int length,const int & item)
{
int first=0,last=length-1;
int mid;
bool found=false;
while (first<=last&&!found)
{
mid =(first+last)/2;
if (list[mid]==item)
found=true;
else if (list[mid]>item)
last=mid-1;
else
first=mid+1;
}
if (found)
return mid;
else if(first>last&&found==false)
{
return -1;
}
else
return binarySearch(list,length,item);
}
Explanation / Answer
int i = 0; change that to
static int i = 0;
should work after that
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.