要求实现堆排序。请填写横线处代码,完善筛选法heapSift函数和堆排序heapSort函数,并把整段代码复制黏贴到代码提交区。
时间: 2024-02-19 13:57:17 浏览: 78
```python
def heapSift(nums, start, end):
root = start
while True:
child = 2 * root + 1
if child > end:
break
if child + 1 <= end and nums[child] < nums[child + 1]: # 右节点比左节点大
child += 1
if nums[root] < nums[child]: # 子节点比父节点大
nums[root], nums[child] = nums[child], nums[root] # 交换父子节点
root = child
else:
break
def heapSort(nums):
# 创建最大堆
for start in range((len(nums) - 2) // 2, -1, -1):
heapSift(nums, start, len(nums) - 1)
# 堆排序
for end in range(len(nums) - 1, 0, -1):
nums[0], nums[end] = nums[end], nums[0] # 将最大值放到最后面
heapSift(nums, 0, end - 1) # 对剩下的元素再次进行堆排序
nums = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
heapSort(nums)
print(nums)
```
阅读全文