Binary search algorithm in python

前端 未结 14 1164
别那么骄傲
别那么骄傲 2020-12-01 11:23

I am trying to implement the binary search in python and have written it as follows. However, I can\'t make it stop whenever needle_element is larger than the largest elemen

14条回答
  •  借酒劲吻你
    2020-12-01 11:46

    In the case that needle_element > array[mid], you currently pass array[mid:] to the recursive call. But you know that array[mid] is too small, so you can pass array[mid+1:] instead (and adjust the returned index accordingly).

    If the needle is larger than all the elements in the array, doing it this way will eventually give you an empty array, and an error will be raised as expected.

    Note: Creating a sub-array each time will result in bad performance for large arrays. It's better to pass in the bounds of the array instead.

提交回复
热议问题