[Python] Binary search always returns -1

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to search through a sorted list consisting of

    sortedList=[2,5,7,9,11,17,222]


    Issue: Unfortunately the code I've written consistently returns -1

    import math

    def binarySearch(li, ele):
    lowest = 0
    highest = len(li)-1
    index = -1
    while highest>=lowest and index==-1:
    mid = int(math.floor((highest+lowest)/2.0))
    if li[mid]==ele:
    index = mid
    elif li[mid]<ele:
    highest = mid-1
    else:
    lowest = mid+1

    return index

    sortedList=[2,5,7,9,11,17,222]
    print(binarySearch(sortedList,11))


    Expected Result: The return of the index for the given integer in sortedList

    Continue reading...

Compartilhe esta Página