赞
踩
def heapify(arr, n, i): largest = i left = 2 * i + 1 right = 2 * i + 2 if left < n and arr[left] > arr[largest]: largest = left if right < n and arr[right] > arr[largest]: 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 max heap for i in range(n // 2 - 1, -1, -1): heapify(arr, n, i) # Extract elements from heap for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # Swap heapify(arr, i, 0) # Test heap sort arr = [12, 11, 13, 5, 6, 7] heap_sort(arr) print("Sorted array is:", arr)
Sorted array is: [5, 6, 7, 11, 12, 13]
微信Alt+A截屏工具
pycharm 2019.3集成开发环境
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。