Getting an index position in a sorted list without built-in functions

Question:

I have been given a task to find the index position of x in a list. I have tried many times, but I always seem to get the wrong index position for some values. The rules are:

  • No built-in functions

  • Valid for all possible x

  • Use divide and conquer as in splitting the list in two until you get the index position

  • The list is sorted

I tried to implement recursive functions, using a while loop, but none of those gave me the right answer.

Here is my code:

list1=[0,1,2,3,4,5,6,7,8] # change to get other values
x=int(input("Enter a number to get its index position: "))

def find_without_built_in_functions(list1, x, start, end):
    if start<=end and x in list1:
        mid=start+((end-1)//2)
        if x==list1[mid]:
            y=mid
            return y
        elif x<list1[mid]:
            return find_without_built_in_functions(list1, x, start+1, mid)
        elif x>list1[mid]:
            return find_without_built_in_functions(list1, x, mid, end+1)
        return -1
print(find_without_built_in_functions(list1, x, 0, len(list1)-1))
Asked By: Stephen Gzy

||

Answers:

  1. Calculate the midpoint as the average of the two endpoints, rounded down.
mid = (start + end) // 2
  1. When the target is less than the middle element, the search space should be shrunk to [start, mid).
return find_without_built_in_functions(list1, x, start, mid - 1)
  1. When the target is larger than the middle element, the search space should be shrunk to (mid, end].
return find_without_built_in_functions(list1, x, mid + 1, end)
  1. return -1 should be outside the if block, so that -1 is returned instead of None when the element does not exist.
Answered By: Unmitigated

The problem with your code is that in the elif branches, you are not updating the value of end and start correctly. You should either increase start or decrease end, depending on which half of the list you are searching in.

def find_without_built_in_functions(list1, x, start, end):
    if start <= end:
        mid = (start + end) // 2
        if list1[mid] == x:
            return mid
        elif list1[mid] > x:
            return find_without_built_in_functions(list1, x, start, mid - 1)
        else:
            return find_without_built_in_functions(list1, x, mid + 1, end)
    else:
        return -1
Answered By: Mehmet Serdar Uz
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.