代码实现堆排序,python
时间: 2024-11-23 11:29:43 浏览: 7
Python实现堆排序.rar
堆排序是一种基于比较的排序算法,它通过构建最大堆或最小堆来进行操作。以下是使用Python实现的简单堆排序算法:
```python
def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
# Build a max heap
for i in range(n // 2 - 1, -1, -1):
heapify(arr, n, i)
# Extract elements one by one
for i in range(n - 1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # Swap
heapify(arr, i, 0)
# 示例
arr = [64, 34, 25, 12, 22, 11, 90]
heap_sort(arr)
print("Sorted array is", arr)
阅读全文