1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| listy = Listy([0, 4, 2, 5, 7, 3, 9 ,13, 15])
def search(listy, key):
# listyの[left:right)から要素がkey以上となる最小の位置を二分探索
def binary_search(listy, key, left, right):
ng = left - 1
ok = right
def is_ok(mid):
return key <= listy.at(mid)
while 1 < abs(ok - ng):
mid = (ok + ng) // 2
if is_ok(mid):
ok = mid
else:
ng = mid
# okの位置にある要素がkeyと等しければ発見成功
found = listy.at(ok) == key
return found, ok
right = 1
while listy.at(right) != -1 and listy.at(right) < key:
right *= 2
left = right // 2
return binary_search(listy, key, left, right)
print(search(listy, -1)) # => (False, 0)
print(search(listy, 0)) # => (True, 0)
print(search(listy, 2)) # => (True, 1)
print(search(listy, 3)) # => (True, 2)
print(search(listy, 13)) # => (True, 7)
print(search(listy, 15)) # => (True, 8)
print(search(listy, 16)) # => (False, 16)
|