Skip to content

Commit dde2e52

Browse files
committed
添加 二分查找算法
1 parent f0f0fca commit dde2e52

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

Data Structures and Algorithms/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
[排序算法](sort)
44

5-
5+
[查找算法](search)
66

77

88

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# 二分查找
2+
3+
二分查找(Binary Search)是将查找的键和子数组的中间键作比较,如果被查找的键小于中间键,就在左子数组继续查找;如果大于中间键,就在右子数组中查找,否则中间键就是要找的元素。
4+
5+
[Python代码](binary_search.py)
6+
7+
```python
8+
import math
9+
10+
def BinarySearch(arr, key):
11+
left = 0
12+
right = len(arr)-1
13+
14+
while left <= right:
15+
mid = math.ceil((left+right)/2)
16+
if arr[mid] == key:
17+
return 1
18+
elif arr[mid]<key:
19+
left = mid+1
20+
else:
21+
right = mid-1
22+
return 0
23+
24+
25+
arr = [10,20,-9,-10,100,-100,77,88,33,21]
26+
arr.sort()
27+
if BinarySearch(arr, -9):
28+
print("Yes")
29+
else:
30+
print("No")
31+
```
32+
33+
参考:
34+
35+
[二分查找(Binary Search)](https://www.cnblogs.com/yedushusheng/p/5524166.html)
36+
37+
[你真的会写二分查找吗](https://www.cnblogs.com/luoxn28/p/5767571.html)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import math
2+
3+
def BinarySearch(arr, key):
4+
left = 0
5+
right = len(arr)-1
6+
7+
while left <= right:
8+
mid = math.ceil((left+right)/2)
9+
if arr[mid] == key:
10+
return 1
11+
elif arr[mid]<key:
12+
left = mid+1
13+
else:
14+
right = mid-1
15+
return 0
16+
17+
18+
arr = [10,20,-9,-10,100,-100,77,88,33,21]
19+
arr.sort()
20+
if BinarySearch(arr, -9):
21+
print("Yes")
22+
else:
23+
print("No")

0 commit comments

Comments
 (0)