From d32287e98e9550b47b403194ba6340bae8f87b4f Mon Sep 17 00:00:00 2001 From: BellCodeEditor <bellcode_dev@bell.ai> Date: Sat, 16 Mar 2024 16:01:54 +0800 Subject: [PATCH] save project --- my_search.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/my_search.py b/my_search.py index 6eaf4dc..ff0ee1d 100644 --- a/my_search.py +++ b/my_search.py @@ -6,4 +6,20 @@ for i in range(1, 101): num = random.choice(alist) # 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置 -def binary_search(alist,num): \ No newline at end of file +def binary_search(alist,num): + low=0 + high=len(alist)-1 + while True: + mid=(low+high)//2#中间索引值 + guess=alist[mid]#中间索引位置对应的数 + if guess==num: + print('找到了') + return mid + elif guess<num: + low=mid+1 + else: + high=mid-1 + return None +result=binary_search(alist,num) +print(result) +print('找到的数是',num,'它在列表中的索引值为',result) \ No newline at end of file -- libgit2 0.25.0