Binary Search not returning properly

I'm trying to do a binary search that returns the location in a vector, given the element content. (EX. i[0] = 4, given 4 the program returns 0.)

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
int findElement(int findItem, vector<int> searchList)
{
    int listSize = searchList.size();
    
    // if there are no elements, return NOT_FOUND
    if (listSize == 0)
        return NOT_FOUND;
    
    // if there is only one element, if that's it, return 0
    // if not, it's not there, so return NOT_FOUND
    if (listSize == 1)
        if (searchList.at(0) == findItem)
            return 0;
        else
            return NOT_FOUND;
    
    // find the middle element
    int middlePosition = listSize / 2;
    int middleItem = searchList[middlePosition];
    
    // compare element at middlePosition to findItem
    if (middleItem == findItem) {
        return middlePosition;
    }
    else if (middleItem > findItem) {
        vector<int> newListBot = copyBottomHalfList(middlePosition, searchList);
        findElement(findItem, newListBot);
    }
    else {
        vector<int> newListTop = copyTopHalfList(middlePosition, searchList);
        findElement(findItem, newListTop);
        
    }
    return 0;
}



The output i'm getting is

findElement(3, myList) returns 0.
findElement(17, myList) returns 0.
findElement(78, myList) returns 2.
findElement(89, myList) returns 0.
findElement( 0, myList) returns 0.
findElement(19, myList) returns 0.
findElement(99, myList) returns 0.
Program ended with exit code: 0



any ideas?
Last edited on
Since you are recursively dividing the list in half, eventually you end up with a very small list that has such return vector positions?

There's no need to do that. Merely move the index, start and endpoint appropriately, but use the full (and original) vector. Copying vectors like this is likely slow, though I can't see how that's done in the two copy functions used here.
you make recursive calls, but don't use their result
also, the index is relative to the subvector, so you would need to add an offset when you check the top half.
Topic archived. No new replies allowed.