Python编程之数据结构与算法练习_005

堆排序算法的Python实现。不废话写原理,直接撸代码

__author__ = 'Orcsir'
# coding: utf-8
import random
# 堆排序
def heap_sort(array: list):
    def heap_insert(array: list, index: int):
        while index != 0 and (array[index] > array[(index - 1) >> 1]):
            array[index], array[(index - 1) >> 1] = array[(index - 1) >> 1], array[index]
            index = (index - 1) >> 1

    def heap_ify(array: list, index: int, heap_size: int):
        left, largest = 2 * index + 1, index
        while left <= heap_size:
            if (left + 1 <= heap_size) and (array[left + 1] > array[left]):
                largest = left + 1
            else:
                largest = left

            if array[index] > array[largest]:
                break

            array[index], array[largest] = array[largest], array[index]
            index, left = largest, 2 * largest + 1

    # create a big root heap
    for i in range(len(array)):
        heap_insert(array, i)
    # sorting
    for i in range(len(array) - 1, 0, -1):
        heap_ify(array, 0, i)
        array[0], array[i] = array[i], array[0]
    return array


# 对数器
def compare(lst_x: list, lst_y: list):
    for i in range(len(lst_x)):
        if lst_x[i] != lst_y[i]:
            return False
    else:
        return True


max_round = 1000
max_value = 1000
arr_length = 1000
for i in range(max_round):
    lst = [random.randint(-max_value, max_value) for _ in range(arr_length)]
    correct_result = sorted(lst)
    heap_sort(lst)
    if not compare(correct_result, lst):
        print("Fucked.")
        print("Fucked sample:{}".format(lst))
        break
else:
    print("Success.")

 

posted @ 2018-04-22 11:21  Orcsir  阅读(182)  评论(0编辑  收藏  举报