Skip to content
Toggle navigation
P
Projects
G
Groups
S
Snippets
Help
Administrator
/
lesson9_3
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
0d8ed407
authored
Nov 27, 2021
by
BellCodeEditor
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
auto save
parent
e7aeaf76
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
67 additions
and
8 deletions
1.py
diy3.py
1.py
0 → 100644
View file @
0d8ed407
def
big_endian
(
arr
,
start
,
end
):
root
=
start
child
=
root
*
2
+
1
#左孩子
while
child
<=
end
:
#孩子比最后一个节点还大,也就意味着最后一个叶子节点了,就得跳出去一次循环,已经调整完毕
if
child
+
1
<=
end
and
arr
[
child
]
<
arr
[
child
+
1
]:
#为了始终让其跟子元素的较大值比较,如果右边大就左换右,左边大的话就默认
child
+=
1
if
arr
[
root
]
<
arr
[
child
]:
#父节点小于子节点直接交换位置,同时坐标也得换,这样下次循环可以准确判断:是否为最底层,
#是不是调整完毕
arr
[
root
],
arr
[
child
]
=
arr
[
child
],
arr
[
root
]
root
=
child
child
=
root
*
2
+
1
else
:
break
def
heap_sort
(
arr
):
#无序区大根堆排序
first
=
len
(
arr
)
//
2
-
1
for
start
in
range
(
first
,
-
1
,
-
1
):
#从下到上,从左到右对每个节点进行调整,循环得到非叶子节点
big_endian
(
arr
,
start
,
len
(
arr
)
-
1
)
#去调整所有的节点
for
end
in
range
(
len
(
arr
)
-
1
,
0
,
-
1
):
arr
[
0
],
arr
[
end
]
=
arr
[
end
],
arr
[
0
]
#顶部尾部互换位置
big_endian
(
arr
,
0
,
end
-
1
)
#重新调整子节点的顺序,从顶开始调整
return
arr
import
random
l
=
[
random
.
randint
(
1
,
50
)
for
i
in
range
(
10
)]
print
(
heap_sort
(
l
))
diy3.py
View file @
0d8ed407
student1
=
{
'语文'
:
91
,
'数学'
:
88
,
'英语'
:
85
}
#堆排序的向下调整函数
student2
=
{
'语文'
:
97
,
'数学'
:
98
,
'英语'
:
90
}
#大根堆的建立方函数
student3
=
{
'语文'
:
95
,
'数学'
:
100
,
'英语'
:
93
}
def
sift
(
li
,
low
,
high
):
#li是指列表,low是指根节点位置,high是指最后一个元素位置
score
=
{
'悟空'
:
student1
,
'诺依'
:
student2
,
'小贝'
:
student3
}
i
=
low
#最开始跟节点的位置
j
=
2
*
i
+
1
#左边下一层孩子节点
tmp
=
li
[
low
]
#把堆顶元素存下来
while
j
<=
high
:
#只要j位置有节点,有数字便可以一直循环
if
j
+
1
<=
high
and
li
[
j
+
1
]
>
li
[
j
]:
#右边孩子有并且右边更大
j
=
j
+
1
#把j指向j+1,右边孩子大于左边,指向右边
if
li
[
j
]
>
tmp
:
li
[
i
]
=
li
[
j
]
i
=
j
#往下看一层
j
=
2
*
j
+
1
else
:
#tmp更大的情况,把tmp放上来
li
[
i
]
=
tmp
#把tmp放到某一级领导的位置上
break
else
:
li
[
i
]
=
tmp
#把tmp放在叶子节点上去
def
heap_sort
(
li
):
name
=
input
(
"名字:"
)
'''构造堆'''
n
=
len
(
li
)
# 查询并打印出输入的名字对应的所有科目的成绩
for
i
in
range
((
n
-
2
)
//
2
,
-
1
,
-
1
):
#(n-2)//2改成n//2-1
sift
(
li
,
i
,
n
-
1
)
#以上表示大根堆构造完成
#挨个吐出数字
for
i
in
range
(
n
-
1
,
-
1
,
-
1
):
#i是指当前堆的最后一个元素
li
[
0
],
li
[
i
]
=
li
[
i
],
li
[
0
]
sift
(
li
,
0
,
i
-
1
)
#i-1是新的堆的high
#以上表示吐出来数字的过程
return
li
import
random
li
=
[]
for
i
in
range
(
7
):
a
=
random
.
randint
(
1
,
50
)
li
.
append
(
a
)
heap_sort
(
li
)
print
(
li
)
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