this is a binary search algorithm for a sapesely sorted dataset.
i’m stuck in line 7, “mid= (first+last)//2”
let me take an example where i’m on line 15 and the condition is met.
then ‘mid’ would be assigned to ‘right’(line 16)
and then it would break out of nested loop(line 17)
then it would go back to line 6 where parent loop begins.
And here the problem is. line 7
3 possible ways.
line 7 would override line 16
line 7 would be dismissed.
I am wrong about something.
i don’t think 1 is right . if it’s right,it would keep resetting mid to (first+last)//2 and turn into infinite loop
is this an exercise? If so, can you please share exercise url? I want to have a look at the instructions.
i would also like to see what the arguments could possible be. Your code feels complex for what it does, but i can’t be certain until i have seen the requirements.
i wrote my own implementation, only check it out if feel like it:
def sparse_search(data, search_val):
print("Data: " + str(data))
print("Search Value: " + str(search_val))
left = 0
right = len(data)-1
mid = len(data) // 2
while left <= mid or right >= mid:
if data[left] == search_val:
return "{0} found at position {1}".format(search_val, left)
elif data[right] == search_val:
return "{0} found at position {1}".format(search_val, right)
left += 1
right -= 1
return "not found"
print(sparse_search('abcd', 'b'))
within parent loop, while first<= last:(line6)
there are 4 if statements. (including elif)
“if not data[mid]”(line8)
and “if data[mid] == search_val”(line24)
and two more elif lines below(line 27, 29)
Is line8 independent condition from line 24, 27, 29?
so “if statement” creates new if block, like line24
and if i want to incorporate new condition into the block
then i have to use elif, not if. like line 27,29. is this right?
<in short, my question is like this>
[if] [if elif elif] [if elif] [if] [if elif] [if else] is this right???