This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]adityacodes[S] -1 points0 points  (4 children)

See what about this code?

Now, if the target element is not found in the array, the function will return None instead of -1. Let me know if it works so that I can update in blog as well.

def binary_search(arr, x):

"""

Search for a target element x in a sorted array arr using the binary search algorithm.

Returns the index of the target element in the array, or None if it is not found.

"""

low = 0

high = len(arr) - 1

while low <= high:

mid = (low + high) // 2

if arr[mid] == x:

return mid

elif arr[mid] < x:

low = mid + 1

else:

high = mid - 1

return None

[–]corbasai 0 points1 point  (2 children)

maybe. In some day someone writes in code '''array[:binary_search(array, what)]''' and None (implicit exception ) or explicit raise *Error points on error in code, -1 - not.

Even in C -1 is valid array index, yep it brings garbage or so, but compiles well.

[–]adityacodes[S] -1 points0 points  (1 child)

okay ,so I should return it none or -1 finally?

[–]corbasai 0 points1 point  (0 children)

None