0

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.

Gsbansal10
  • 303
  • 5
  • 12
  • How about using `set` – ZisIsNotZis Oct 25 '18 at 08:39
  • could you please expand on your idea. As far as I know, sets are used to remove duplicate items and to perform mathematical set operations like intersection, union etc. I am not aware of the search facility in set. Please elaborate. – Gsbansal10 Oct 25 '18 at 08:48
  • You should definitely check the duplicate URL first. Anyway, `set` is internally hashed, therefore looking up an element in `set` (ideally) works like indexing an array and takes constant time (i.e. `O(1)`) which is faster than `O(log(n))` of binary search. – ZisIsNotZis Oct 25 '18 at 08:52
  • Thanks for your inputs and patience. This helped a lot. – Gsbansal10 Oct 25 '18 at 09:00

0 Answers0