Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
level3-lesson16-diy2
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
0790b1c7
authored
May 04, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
adaf6f8a
Show whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
47 additions
and
0 deletions
knsearch.py
my_search.py
knsearch.py
0 → 100644
View file @
0790b1c7
'''
题目:
有一个无序的序列list_c = [
37, 99, 73, 48, 47, 40, 40, 25, 99, 51], 请先排序并打印输出。
分别尝试插入
[
20,40,41,100]到序列中合适的位置,保证其有序。
'''
list_c
=
[
37
,
99
,
73
,
48
,
47
,
40
,
40
,
25
,
99
,
51
,
99
]
list_s
=
[
20
,
40
,
41
,
100
]
#先排序
order_list
=
sorted
(
list_c
)
print
(
order_list
)
#浅复制,保留原来数据
ret
=
order_list
[:]
def
insert_sort
(
ret
,
num
):
low
=
0
#索引起点
high
=
len
(
ret
)
#索引终点
while
low
<
high
:
# 起点索引大于或等于列表最后一个元素的索引,条件无法进入。
mid
=
(
low
+
high
)
//
2
# 取列表中间点的索引
if
num
<
ret
[
mid
]:
# 条件判断,如果待插入列表的值小于有序列表对应mid索引的值,就向左查询
high
=
mid
-
1
# 同时确认这个中间点mid索引就是ret列表的high最高索引
else
:
# 如果待插入列表的值大于有序列表对应mid索引的值,就向右查询,求中点
low
=
mid
+
1
# 同时确认这个中间点mid索引就是ret列表的开始索引low的值。
return
low
# 这个开始索引low就是最终计算出来的待插入索引的位置low,所以返回low
for
num
in
list_s
:
# 循环去取待插入列表的元素。
index
=
insert_sort
(
ret
,
num
)
# 调用上面的函数取出插入元素索引值
ret
.
insert
(
index
,
num
)
# 就地插入对应索引的值到列表ret中.
print
(
ret
)
# 打印插入元素后的列表
my_search.py
View file @
0790b1c7
...
...
@@ -7,3 +7,19 @@ num = random.choice(alist)
# 请完善二分查找函数binary_search(),查找出num在列表alist里面的索引位置
def
binary_search
(
alist
,
num
):
low
=
0
high
=
len
(
alist
)
-
1
while
low
<=
high
:
mid
=
(
low
+
high
)
//
2
guess
=
alist
[
mid
]
if
guess
==
num
:
return
mid
elif
guess
<
num
:
low
=
mid
+
1
else
:
high
=
mid
-
1
return
None
result
=
binary_search
(
alist
,
num
)
print
(
"给的数是:"
,
num
)
print
(
"他在列表里的索引是:"
,
result
)
\ 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