#include <iostream>
usingnamespace std;
int sortera(int array[], int storlek);
int binary_search(int array[], int objekt, int left, int right);
int main()
{
constint s(10);
int v[s], i, objekt;
for(i = 0; i < s; i++)
{
cin >> v[i];
}
sortera(v, s);
cin >> objekt;
binary_search(v, objekt, v[0], v[9]);
}
int binary_search(int array[], int objekt, int left, int right)
{
while(left <= right)
{
int middle = (left + right) /2;
if(array[middle] == objekt)
return middle;
elseif(array[middle] > objekt)
right = middle -1;
else
left = middle +1;
}//END while
return -1;
}//END binary_search();
Question 1.
Is it possible to change the binary_search(v, objekt, v[0], v[9]); to be more flexible, so instead of having to change both the constant value of s() AND v[] to add more numbers in my array, only change the constant value of s?
I want it to be as simple as possible to change the number of values in my array. As it is now I have to change the code at two places...
Question 2.
How do I make use of the return value from my function? I tried using
1 2 3
int value;
value=binary_search(array[], objekt, left, right);
cout << value;
1)
I think the call to binary_search is wrong because left and right should be indices. The call should look like binary_search(v, objekt, 0, 9);. To answer your question, you can change 9 into s-1, binary_search(v, objekt, 0, s - 1);.
2)
Why have you changed the arguments you pass to the function? This should work fine:
1 2 3
int value;
value=binary_search(v, objekt, 0, s - 1);
cout << value;
I don't know why I can't remember the easy stuff, but I always get it wrong. Thank you. =)
I tested your suggestion on my second question, and it works. But it has a few problems...
If I enter 11..22..33..44..55..aso and then search for the value 33 using my binary_search() function, and then use the return value like in this example:
In binary_search you are returning the position at which the number you're looking for is found.
So to print the value of the element in that position you have to do
cout << endl << "Found value " << array[answer];
Or did you want for binary_search() to return the value instead of the position?