python 实现堆排序算法代码,需要的朋友可以参考下
开源计算机视觉库拥有超过2500个算法,提供详细的文档和实时计算机视觉的示例代码。它可以在Windows、Linux、Mac OS X、Android、iOS上运行,并通过JavaScript在您的浏览器中使用。语言:C++、Python、Julia、Javascript主页:https://opencv.org问答论坛:https://forum.opencv.org/文档:https://docs.opencv.org源代码:https://github.com/opencv请特别关注我们的教程!ht
20
代码如下:
#!/usr/bin/python
import sys
def left_child(node):
return
node * 2 + 1
def
right
_child(node):
return node * 2 + 2
def parent(node):
if (node % 2):
return (i - 1) / 2
else:
return (i - 2) / 2
def max_heapify(
array
, i, heap_size):
l = left_child(i)
r = right_child(i)
largest = i
if l < heap_size and array[l] > array[i]:
largest = l
if r < heap_size and array[r] > array[largest]:
largest = r
if largest != i:
array[i], array[largest] = array[largest], array[i]
max_heapify(array, largest, heap_size)
def build_max_heap(array):
for i in
range
(len(array) / 2, -1, -1):
max_heapify(array, i, len(array))
def heap_sort(array):
build_max_heap(array)
for i in range(len(array) - 1, 0, -1):
array[0], array[i] = array[i], array[0]
max_heapify(array, 0, i)
if name == "
main
":
array = [0, 2, 6, 98, 34, -5, 23, 11, 89, 100, 7]
heap_sort(array)
for a in array:
sys.stdout.write("%d " % a)以上就是python堆排序算法实例代码的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号