Python 实现二分法

2018-10-30  本文已影响42人  爱吃猫的老虎

```

# 中间位置是向上取整

import math

a = [0,1,2,3,4,5,6,7,8,9,10]

def halfSearch(key,list):

start = 0        

    end = len(list)-1

    index = math.ceil((start + end)/2)

while start <= end:

if list[index] ==key:

print(index)

break

    elif key >list[index]:

start = index +1

        index = math.ceil((start-1 + end) /2)

continue

    else:

end = index -1

        index = math.ceil((start + end-1) /2)

continue

```

上一篇下一篇

猜你喜欢

热点阅读