0
\$\begingroup\$
def search(nums, target):
    for i in range(len(nums)):
        if nums[i] == target:
            return i
        if nums[i] == None:
          return -1

I think this code will be good for most cases in binary search but in some cases might need a better version of the code that is O(log n).

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is not a binary search, this is a linear search, which is almost the opposite of binary search. Calling this "binary search" is very misleading. \$\endgroup\$ Dec 17, 2022 at 13:48
  • \$\begingroup\$ So what exactly is your question here? \$\endgroup\$
    – Juho
    Dec 17, 2022 at 13:51
  • \$\begingroup\$ Is nums such that 0 <= i <= j < len(nums) implies nums[i] <= nums[j] ? \$\endgroup\$
    – fgrieu
    Dec 17, 2022 at 15:17

2 Answers 2

11
\$\begingroup\$

It's not really a binary search if it is not O(log(n)).

Binary search only works on sorted inputs and it takes advantage of the fact that it is sorted to achieve logarithmic complexity.

So it's quite the opposite - your version will be significantly inefficient for almost all programs that could use true binary search instead.

See, for example, here how to implement binary search in python

\$\endgroup\$
1
\$\begingroup\$

search([2, None, 3], 3) will return -1, and I think users will find this unexpected. That is, the function doesn't just search, it has an added effect of returning -1 when it finds a None value.

The recommended way to check if a value is None is using the is keyword: if value is None:

When using both the index and the item during an iteration, the enumerate function is practical.

def search(nums, target):
    for index, num in enumerate(nums):
        if num == target:
            return index
       
    return -1
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.