1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| import random import datetime
def randList (min, max, l): min,max = (int(min),int(max)) if min <= max else (int(max),int(min)) l = int(abs(l)) if l else 0 list = [] for i in range(l): list.append(random.randint(min,max)) return list
def binarySearch (arr, l, r, x): if r >= l: mid = int(l + (r - l)/2) if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) else: return binarySearch(arr, mid+1, r, x) else: return -1
arr = randList (1, 50, 20) arr.sort() print ("随机数列为",arr) x = 20
startTime = datetime.datetime.now()
result = binarySearch(arr, 0, len(arr)-1, x) if result != -1: print ("元素 %d 在数组中的索引为 %d" %(x, result)) else: print ("元素不在数组中")
endTime = datetime.datetime.now() print ("执行时间%dms" % ((endTime - startTime).seconds * 1000 + (endTime - startTime).microseconds/1000))
|