[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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
  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:
-------

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.