-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.py
More file actions
56 lines (39 loc) · 989 Bytes
/
BinarySearch.py
File metadata and controls
56 lines (39 loc) · 989 Bytes
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
56
#!usr/bin/python#coding=utf-8
#二分查找
#执行方式: python BinarySearch.py tinyW.txt < tinyT.txt
import sys
sys.path.append(r"../class/")
import StdIn
def BinarySearch(whileList,keyIn):
print("Binary Search Function")
#必须是升序序列才能使用二分查找
whileList.sort()
print(whileListIn)
print("keyIn={}".format(keyIn))
lo=0
hi=len(whileList)-1
while lo <= hi :
mid =lo + (hi-lo)//2
if whileList[mid] == keyIn:
return mid
elif whileList[mid] < keyIn:
lo = mid+1
else:
hi = mid-1
else:
return -1
if __name__ == '__main__':
print("Task excute start...")
keyIn=0
whileListIn = StdIn.readInt(sys.argv[1])
while True:
try:
keyIn=int(input())
result = BinarySearch(whileListIn,keyIn)
if result != -1:
print("keyIn found! result = ",result)
else:
print("keyIn not found!")
except EOFError:
print("Task excute is finish!")
break