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
dd641498
authored
Aug 06, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
save project
parent
b250abfe
Hide whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
31 additions
and
2 deletions
binary_search.py
binary_search.py
View file @
dd641498
# 使用二分查找法,找出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
]
# 0, 1, 2, 3, 4 , 5 , 6 , 7 , 8 , 9
'''
1.最低索引low 0
2.最高索引high 列表长度-1
3.要查找的数据num
4.while True构建循环
5.中间索引mid (low+high) // 2
6.中间值guess 列表名[索引]
7.判断中间值是否是要找的数是的话就输出找到了退出循环
8.判断中间值与要找的数的大小,如果中间值大,范围就在左边,改变最高索引为中间值-1
9.判断中间值与要找的数的大小,如果要找的值大,范围就在右边,改变最低索引为中间值+1
10.如果最高索引小于最低索引,就是没找到,输出没找到退出循环
'''
def
fnuc
(
num_list
,
num
)
low
=
0
high
=
len
(
num_list
)
-
1
num
=
9
while
True
:
mid
=
(
low
+
high
)
//
2
guess
=
num_list
[
mid
]
if
guess
==
num
:
print
(
'找到了'
)
break
elif
high
<
low
:
print
(
'没找到'
)
break
elif
guess
>
num
:
high
=
mid
-
1
else
:
low
=
mid
+
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