[Problem] Binary Search

Dear C++ Community

I kindly do not understand ,why the code does not output the number searched for? (it was suppose to be right) this was posted by my lecturer.

 ``12345678910111213141516171819202122232425262728293031323334`` `````` int binary_search(char data[],int size, char value){ int lower, middle, upper; lower = 0; upper = size - 1; while(true){ for(int i = lower; i <= upper; i++){ cout<< data[i] << ' '; } cout<< endl; middle = (lower + upper) / 2; if(data[middle] == value){ return middle; } else if(lower >= upper){ return -1; } else if(value < data[middle]){ upper = middle - 1; } else{ lower = middle + 1; } } } int main(){ char list[20] = "12345678"; cout << binary_search(list, 8, '7') << endl; cout << binary_search(list, 8, '0') << endl; }``````

Output:
-------

 ``12345678910111213141516`` ``````1 2 3 4 5 6 7 8 5 6 7 8 7 8 6 1 2 3 4 5 6 7 8 1 2 3 1 -1 ``````
The binary search finds the index of the item you are searching for.

'7' is in the list, at index 6.

'0' is not in the list, so -1 (an invalid index) is returned.

Hope this helps.
Thank you very much. I really appreciate all your help.
Topic archived. No new replies allowed.