Binary Search Not Working

I have no clue why this search isn't working.

Two majors problems
(1) As is it always returns false
(2) It would recognize valid IDs if instead of setting found to true, I just returned true, but I don't want to do it like that, and if there was an invalid account number it would go into an infinite loop

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
bool binarySearch(int *validAccounts, int length, int account)
{

    int first = 0;
    int last = length;
    int middle = (first + last) / 2;
    bool found = false;

    while(!found && first <= last  )
    {
        middle = (first + last) / 2;

        if(validAccounts[middle] == account)
        {
            found = true;
        }
        else if(account < validAccounts[middle])
        {
            last = middle - 1;
        }
        else
        {
            first = middle + 1;
        }
    }
    return false;
}
Try returning found instead of false.
ah figured it out, I need a second variable to return. One bool for the flag and one for the return value otherwise it always returns false.

IE the found is only a flag for the loop

the second variable is set to false and this way can return true if it finds the value

With one variable for loop and return there is no way to share the duties,

IE always return false, or even if it is found to be true, there it will still be set to false
Topic archived. No new replies allowed.