A
alacrite
#include <iostream>
#include <vector>
using namespace std;
int binarySearch(vector<int>, int, int, int);
int main()
{
vector<int> arrInt;
for(int i=0; i<1000; i++)
{
arrInt.push_back(i);
}
int pos = 0;
if(pos=binarySearch(arrInt, 12, 0, 999))
cout<<"pos "<<pos<<endl;
//cout<<arrInt[pos];
else
cout<<"Not Found"<<endl;
return 0;
}
int binarySearch(vector<int> list, int value, int left, int right)
{
int mid = (left+right)/2;
if(value>list[mid])
binarySearch(list, value, mid, right);
else if (value<list[mid])
binarySearch(list, value, left, mid);
else if(value==list[mid])
{
cout<<"about to return "<<mid<<endl;
return mid;
}
else
return -1;
}
When this runs the output I get it:
about to return 12
pos 1244568
expected output:
about to return 12
pos 12
Anyone know why the return value from binarySearch is wrong?
thanks!
#include <vector>
using namespace std;
int binarySearch(vector<int>, int, int, int);
int main()
{
vector<int> arrInt;
for(int i=0; i<1000; i++)
{
arrInt.push_back(i);
}
int pos = 0;
if(pos=binarySearch(arrInt, 12, 0, 999))
cout<<"pos "<<pos<<endl;
//cout<<arrInt[pos];
else
cout<<"Not Found"<<endl;
return 0;
}
int binarySearch(vector<int> list, int value, int left, int right)
{
int mid = (left+right)/2;
if(value>list[mid])
binarySearch(list, value, mid, right);
else if (value<list[mid])
binarySearch(list, value, left, mid);
else if(value==list[mid])
{
cout<<"about to return "<<mid<<endl;
return mid;
}
else
return -1;
}
When this runs the output I get it:
about to return 12
pos 1244568
expected output:
about to return 12
pos 12
Anyone know why the return value from binarySearch is wrong?
thanks!