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
41071244
authored
Feb 28, 2026
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
c7faa222
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
14 additions
and
14 deletions
binary_search.py
binary_search.py
View file @
41071244
# 使用二分查找法,找出9和20在列表里面的索引
# 使用二分查找法,找出9和20在列表里面的索引
a_num
=
20
a_num
=
20
#要查找的数字
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
,
32
,
64
]
num_list
=
[
1
,
3
,
5
,
8
,
11
,
15
,
17
,
18
,
20
,
21
,
32
,
64
]
#列表
low
=
0
low
=
0
#最小的索引
high
=
len
(
num_list
)
-
1
high
=
len
(
num_list
)
-
1
#最高的索引列表数值减一
while
low
<=
high
:
while
low
<=
high
:
重复执行直到最小的小于等于最高的
mid
=
(
low
+
high
)
//
2
#向下取整
mid
=
(
low
+
high
)
//
2
#向下取整
guess
=
num_list
[
mid
]
guess
=
num_list
[
mid
]
#取出中间值
if
guess
==
a_num
:
if
guess
==
a_num
:
#如果取得中间值等于需要的数值
print
(
"找到了他的索引是"
,
mid
)
print
(
"找到了他的索引是"
,
mid
)
#那么打印找到了索引在。。
break
break
#退出循环
elif
guess
<
a_num
:
elif
guess
<
a_num
:
#否则如果中间值小于需要的数值
low
=
mid
+
1
low
=
mid
+
1
#最低等于中间索引值加1
else
:
else
:
#否则中间值大于需要的数值
high
=
mid
-
1
high
=
mid
-
1
#最大索引等于中间索引值减1
\ No newline at end of file
\ No newline at end of file
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