How do I call a binary searchin a loop

How can I loop through a data field with a binary search, looking for multiple values? Please, I don't want to know another, more efficient way, I want to do it this way to understand the concepts. Also my data is indeed sorted before the call is made. The data are all of type double and I'm asking for an int (97 here) It works, kinda. I keep getting numbers that fall outside the range 93, 92, 90 for example. Also, my target values lie smack in the middle of the data, so the midpoint, and 4 or 5 values above and below it are also 97. Any help would be appreciated.


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
35
36
37
38
39
40
41


// Loop calling the search
int j = bSearch(ave, count, 97.0);
int i = bSearch(ave, count, 97.0);
int k;
while(k != -1 )
{
    k = bSearch(ave, j, 97);
    cout << j << " :"<< id[j] << " " << ave[j] << endl;
    cout << i << ":"<< id[i] << " " << ave[i] << endl;
    j--;
    i++;
}

// search (very standard)
int bSearch(double array[], int size, double value)
{
    int first = 0;
    int last = size - 1;
    int middle = (first + last)/2;
    bool found = false;
    int pos = -1;

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

        if(array[middle] == value)
        {
            pos = middle;
            found = true;
        }
        else if(array[middle] > value)
            first = middle + 1;
        else
            last = middle - 1;

    }
    return pos;
}


SONOFA

Also, when I actually search for the decimal is drops a steamer on me, somehow only returning a couple values out of bounds. ACTUALLY this isn't working at all. When I ask for the exact decimal value it says not found, and when I ask for a value that appears only once ex 93 or 93.1754 (the exact value. But when I search for a value that there's like a dozen of it finds them all, and then throws a couple extras for fun. I am about to chuck my computer through a wall.
Last edited on
Topic archived. No new replies allowed.