Python堆排序
def adjust_deap(arr, p, b): while True: if 2 * p + 1 > b - 1: break elif 2 * p + 2 < b and arr[2 * p + 2] > arr[2 * p + 1] and arr[2 * p + 2] > arr[p]: arr[p], arr[2 * p + 2] = arr[2 * p + 2], arr[p] p = 2 * p + 2 elif arr[2 * p + 1] > arr[p]: arr[p], arr[2 * p + 1] = arr[2 * p + 1], arr[p] p = 2 * p + 1 else: break return arr def create_heap(arr): m = len(arr) / 2 - 1 while m > -1: arr = adjust_deap(arr, m, len(arr)) m -= 1 return arr def heap_sort(arr): m = len(arr) - 1 while m: arr[0], arr[m] = arr[m], arr[0] arr = adjust_deap(arr, 0, m) m -= 1 return arr a = [4, 2, 4, 7, 5, 3, 6, 8, 9, 35, 4, 2, 45, 65, 23] heap = create_heap(a) print heap_sort(heap)