The first binary search. 161P of the algorithm picture book written in C language to python in your own way. It will not work if you enter a number that is not in the list. It is assumed that the numbers in the list are arranged in ascending order.

`nibun.py`

```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
x = [1, 8, 14, 23, 44, 55, 67, 88, 103, 146]
print x
print "Enter the number you want to find"
i = int(raw_input())
low = 0
high = len(x)
#t is the middle number
t = (low + high) / 2
#Search until the lower limit low of the search becomes the upper limit high
#When low reaches high, the number was not found
while (low<=high):
if (i==x[t]):
break
elif (i > x[t]):
low = t + 1
elif (i < x[t]):
high = t - 1
t = (low + high) / 2
if (i==x[t]):
print str(t + 1) + "Is in the second"
else:
print "There is none"
```

Recommended Posts