P
P
pinguine2017-10-20 19:57:17
Python
pinguine, 2017-10-20 19:57:17

How to add element existence check to binary search algorithm?

There is a binary search algorithm that, depending on the value of the last variable, returns the first or last occurrence of an element in an array

def binary_search(l, key, last):
    low = 0
    high = len(l)-1
    while low <= high: 
        mid = (low + high) // 2
        midVal = l[mid];
        if (midVal < key or (last and midVal == key)): low = mid + 1
        elif (midVal > key or ((not last) and midVal == key)): high = mid - 1
    return high if last else low

How to add element existence check to binary search algorithm? The type check doesn't work because it's just another pass through the array in a loop. if key in list

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
apreci, 2017-10-20
@apreci

def binary_search(elem, array):
    left = 0
    right = len(array)

    while left != right:
        med = (left + right) // 2

        if array[med] < elem:
            left = med + 1
        elif array[med] > elem:
            right = med
        else:
            return med

    return -1

If there is no element, -1 is returned.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question