add 堆排序.
This commit is contained in:
parent
94021b3455
commit
f014389281
@ -2,9 +2,10 @@
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/venv" />
|
||||
</content>
|
||||
<orderEntry type="jdk" jdkName="Python 3.10 (Algorithm)" jdkType="Python SDK" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.12 (Algorithm)" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
@ -1,4 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.10 (Algorithm)" project-jdk-type="Python SDK" />
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.12 (Algorithm)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (Algorithm)" project-jdk-type="Python SDK" />
|
||||
</project>
|
0
learn_sort/__init__.py
Normal file
0
learn_sort/__init__.py
Normal file
31
learn_sort/heap.py
Normal file
31
learn_sort/heap.py
Normal file
@ -0,0 +1,31 @@
|
||||
def heapify(nums, start, end):
|
||||
parent = start
|
||||
son = parent * 2 + 1
|
||||
while son <= end:
|
||||
if son + 1 <= end and nums[son] < nums[son + 1]:
|
||||
son += 1
|
||||
if nums[parent] > nums[son]:
|
||||
return
|
||||
else:
|
||||
nums[parent], nums[son] = nums[son], nums[parent]
|
||||
parent = son
|
||||
son = parent * 2 + 1
|
||||
|
||||
|
||||
def heap_sort(nums):
|
||||
n = len(nums)
|
||||
for i in range(n // 2 - 1, -1, -1):
|
||||
heapify(nums, i, n - 1)
|
||||
print(nums)
|
||||
|
||||
for i in range(n - 1, 0, -1):
|
||||
nums[0], nums[i] = nums[i], nums[0]
|
||||
heapify(nums, 0, i - 1)
|
||||
print(nums)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# https://leetcode.cn/problems/sort-an-array/description/
|
||||
_nums = [7, 10, 13, 15, 4, 20, 19, 8]
|
||||
heap_sort(_nums)
|
||||
print(_nums)
|
Loading…
Reference in New Issue
Block a user