python使用堆排序算法排序序列:49 38 65 97 13 27 49
时间: 2023-11-27 18:53:15 浏览: 66
以下是使用 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//2 - 1, -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
arr = [49, 38, 65, 97, 13, 27, 49]
sorted_arr = heapSort(arr)
print(sorted_arr)
```
执行后输出结果为:
```
[13, 27, 38, 49, 49, 65, 97]
```
因此,堆排序算法对序列 [49, 38, 65, 97, 13, 27, 49] 进行排序后,结果为 [13, 27, 38, 49, 49, 65, 97]。
阅读全文