用Python写一个堆排序
时间: 2023-07-01 07:21:36 浏览: 86
好的,下面是用 Python 实现堆排序的代码:
```python
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def heapSort(arr):
n = len(arr)
for i in range(n, -1, -1):
heapify(arr, n, i)
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i]
heapify(arr, i, 0)
return arr
```
使用示例:
```python
arr = [12, 11, 13, 5, 6, 7]
result = heapSort(arr)
print(result)
```
输出结果:
```
[5, 6, 7, 11, 12, 13]
```
希望能够帮到你!
阅读全文