I am working on the algorithm of a project Euler problem. In this, I am processing a large list of numbers with possibly millions of entries in the list. I know beforehand that the list is sorted and I want to check if a particular element is in it or not. I can do it like:
if element in array:
#do something
else:
# do something else
or like:
if((array.index(element)>=0):
# do something
else:
# do something else
But I know it searches for the element linearly, which takes much time. It pains me that even if the list is sorted, it searches for it linearly. Is there a way that I can tell the compiler to search for the element using binary search, like a default parameter like:
if(array.index(element, binary_search=False):
#do something
so that I can make the second parameter to True
and it works as expected. Or do I have to write the binary search function
by myself and use it instead of the builtin index
method or the in
operator?
I am new to Python. Please bear with my ignorance. I searched for it extensively but couldn't find the exact answer. Thanks in advance.