Goodspeed

导航

二分法查找(Python版)

代码
#! /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,100for 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)
        
        


posted on 2010-07-19 17:06  Goodspeed  阅读(1617)  评论(0编辑  收藏  举报