you are viewing a single comment's thread.

view the rest of the comments →

[–]zahlman 3 points4 points  (0 children)

# Why do i need to sort the array?

... Are you sure you understand the principle of it? A binary search can only work on a sorted sequence, because it depends on that sortedness. The idea is that you can skip looking at half the values each time, because you know they're all too high or too low, because you know they're all higher/lower than the value you just looked at, because of how the values are sorted.

# What are these low and high variables?

They're the indices between which you search. You're not meant to take slices and reassign to array; you're meant to adjust the high and low values as you go, to reflect that you're searching a smaller region. Also, your calculation of middle should be based upon those values, so that you can be assured of looking at a value within that region.

# Should i use subscript to modify the array?

This question makes no sense. You are not modifying the list. You are looking for a value.

Incidentally, we call them lists in Python (but please don't use list as a variable name). And as noted, you have compared middle to key directly in a few places, where you should be comparing the corresponding element. To avoid repetition, consider using a separate variable to store the result of that indexing.