代码
#! /usr/bin/env python
# coding=utf-8
import random
def dichotomy(L,K,Index):
if(len(L) == 1):
return Index
length = len(L) / 2
hit = L[length]
if(hit == K):
return Index + length
else:
if hit > K:
return dichotomy(L[:length],K,Index)
else:
return dichotomy(L[length + 1:],K,Index + length + 1)
if __name__ == '__main__':
L = [random.randint(1,100) for i in range(1,20)]
L = {}.fromkeys(L).keys()
L.sort()
K = random.choice(L)
print L,K
index = dichotomy(L,K,0)
print index,L.index(K)
# coding=utf-8
import random
def dichotomy(L,K,Index):
if(len(L) == 1):
return Index
length = len(L) / 2
hit = L[length]
if(hit == K):
return Index + length
else:
if hit > K:
return dichotomy(L[:length],K,Index)
else:
return dichotomy(L[length + 1:],K,Index + length + 1)
if __name__ == '__main__':
L = [random.randint(1,100) for i in range(1,20)]
L = {}.fromkeys(L).keys()
L.sort()
K = random.choice(L)
print L,K
index = dichotomy(L,K,0)
print index,L.index(K)