Skip to content

Commit 6d795f3

Browse files
authored
Merge pull request #72 from dengshilong/master
fix: 修复二分查找算法
2 parents 360aa1d + 3827dfe commit 6d795f3

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.idea

Readme.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1569,21 +1569,21 @@ def node(l1, l2):
15691569
```python
15701570

15711571
#coding:utf-8
1572-
def binary_search(list,item):
1572+
def binary_search(list, item):
15731573
low = 0
1574-
high = len(list)-1
1575-
while low<=high:
1576-
mid = (low+high)/2
1574+
high = len(list) - 1
1575+
while low <= high:
1576+
mid = (high - low) / 2 + low # 避免(high + low) / 2溢出
15771577
guess = list[mid]
1578-
if guess>item:
1579-
high = mid-1
1580-
elif guess<item:
1581-
low = mid+1
1578+
if guess > item:
1579+
high = mid - 1
1580+
elif guess < item:
1581+
low = mid + 1
15821582
else:
15831583
return mid
15841584
return None
15851585
mylist = [1,3,5,7,9]
1586-
print binary_search(mylist,3)
1586+
print binary_search(mylist, 3)
15871587

15881588
```
15891589

0 commit comments

Comments
 (0)