-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# 返回 x 在 arr 中的索引,如果不存在返回 -1 | ||
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 = [ 2, 3, 4, 10, 40 ] | ||
x = 10 | ||
|
||
# 函数调用 | ||
result = binarySearch(arr, 0, len(arr)-1, x) | ||
|
||
if result != -1: | ||
print ("元素在数组中的索引为 %d" % result ) | ||
else: | ||
print ("元素不在数组中") |