代码:
#! /usr/bin/env python #coding=utf-8 import random,copy def heap_sort_helper(lst,left,right): # max heapify current_value = lst[left] child = 2 * left + 1 while (child <= right): if (child < right and lst[child] < lst[child+1]): child = child + 1 if (current_value > lst[child]): break else: lst[(child-1)>>1] = lst[child] child = 2 * child + 1 lst[(child-1)>>1] = current_value def heap_sort(lst): # build heap for i in range((len(lst)-1)>>1,-1,-1): heap_sort_helper(lst,i,len(lst)-1) for i in range(len(lst)-1,0,-1): lst[i],lst[0] = lst[0],lst[i] heap_sort_helper(lst,0,i-1) if __name__ == "__main__": lst = [random.randint(0,20) for i in range(10)] lst2 = copy.deepcopy(lst) lst2.sort() print(lst) print(lst2) heap_sort(lst) print(lst)
测试数据:
[18, 3, 1, 20, 7, 5, 4, 10, 16, 6]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
[1, 3, 4, 5, 6, 7, 10, 16, 18, 20]
时间: 2024-10-12 15:46:01