二分法
#!/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)
Aimer,c'est partager