Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
level3-lesson16-diy1
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Snippets
Members
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit
d5b84152
authored
Aug 14, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
b250abfe
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
18 additions
and
2 deletions
binary_search.py
binary_search.py
View file @
d5b84152
# 使用二分查找法,找出9和20在列表里面的索引
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
\ No newline at end of file
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
]
num
=
9
# 查找的数字
low
=
0
# 最低索引
high
=
len
(
num_list
)
-
1
# 最高索引
while
True
:
# 无限循环
mid
=
(
low
+
high
)
//
20
# 中间索引
if
num_list
[
mid
]
==
num
:
# 中间值 是否等于 要查找的数
print
(
'找到了'
,
mid
)
# 输出找到了和索引
break
# 跳出循环
elif
low
>
high
:
# 最低索引大于最高索引
print
(
'没找到'
)
# 输出没找到
break
# 跳出循环
elif
num_list
[
mid
]
<
num
:
# 中间值 小于 要查找的数
low
=
mid
+
1
# 最低索引等于中间索引加1
else
:
# 否则
high
=
mid
-
1
# 最高索引等于中间索引 减 1
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment