0

Algorithm is working but can only find if the value exist or not. I want to find the index in case it exists. How can I do it?

def binarySearch(arr, num):
  if len(arr) == 1: #base case
    if arr[0] == num:
      return arr[0] #found
    else:
      return None #not found

  mid = int(len(arr)/2) 
  if arr[mid] > num:
    return binarySearch(arr[:mid], num)
  else:
    return binarySearch(arr[mid:], num)

print(binarySearch([1,2,3,4], 7)) #None
print(binarySearch([1,2,3,4], 3)) #3
print(binarySearch([1,2,3,4], 4)) #4
print(binarySearch([1], 2)) #None
print(binarySearch([1,2], 2)) #2
2
  • pass the index around. Commented Feb 22, 2018 at 10:24
  • Rather than passing a sliced array into the recursion, you should consider passing start and end pointers. Commented Feb 22, 2018 at 10:25

1 Answer 1

1

Just pass the index around like this:

def binarySearch(arr, num, idx=0):
  if len(arr) == 1: #base case
    if arr[0] == num:
      return idx
    else:
      return None #not found

  mid = len(arr) // 2
  if arr[mid] > num:
    return binarySearch(arr[:mid], num, idx)
  else:
    return binarySearch(arr[mid:], num, idx + mid)

print(binarySearch([1,2,3,4], 7)) #None
print(binarySearch([1,2,3,4], 3)) #2
print(binarySearch([1,2,3,4], 4)) #3
print(binarySearch([1], 2)) #None
print(binarySearch([1,2], 2)) #1

It now returns the index of the number if it has been found or None if it's not in the list.

As mentioned in the comments: consider passing start and end values instead of copying the list at every recursion. It's faster and easier to write and to read.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.