二分法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# O(logn)
' binary_search '
__author__ = 'chris'

import random
import string

def binary_search(list,item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = int((low + high)/2)
        guess = list[mid]
        if item == guess:
            return mid
        elif item < guess:
            high = mid - 1
        else:
            low = mid + 1
    return None

arr = []
for i in range(50):
    str = ''.join(random.sample((string.ascii_letters + string.digits), 8))
    if i == 13:
        arr.append('hello_binarysearch')
        continue
    arr.append(str)

arr.sort()
print(arr)
res = binary_search(arr,'hello_binarysearch')
print(res)

 

posted @ 2019-05-30 11:02  Chris,Cai  阅读(152)  评论(0编辑  收藏  举报