如何在python中实现heapify函数?

时间:2014-07-14 04:07:16

标签: python algorithm heap

我正在学习堆并尝试实现heapify功能。我理解算法,但是我在给定的heapify函数编写测试用例时遇到了麻烦。有人可以给出一个测试用例的例子吗?

class Heap:
    def __init__(self, sorting_key):
        self.heap = list()
        self.mapping = dict()
        self.sorting_key = sorting_key

    def __len__(self):
        return len(self.heap)

    #
    # STANDARD HEAP OPERATIONS
    #

    def heapify_up(self, child):
        """Standard heapify operation, as described in CLRS.
        Works by swapping the element originially at index child in the heap
        with its parent until the heap property is satisfied. Modifies the
        appropriate heap attribute

        Args:
            child: Index of the element that violates the heap property

        Returns:
            None
        """
        parent = (child - 1) / 2
        # Swaps the element originally at the index child with its parent
        # until the value of the specifed attribute of the parent is greater
        # than the value of the specified attribute of the element itself
        while (getattr(self.heap[parent], self.sorting_key) <
               getattr(self.heap[child], self.sorting_key)):
            if (parent == -1):
                # This means child was 0, which means we have reached the
                # top of the heap
                return

            # Swap the mappings as well to ensure that future references in
            # the mapping dict refer to the correct position of the object in
            # the heap
            self.mapping[self.heap[parent].player] = child
            self.mapping[self.heap[child].player] = parent

            # Swap the parent and the child
            temp = self.heap[parent]
            self.heap[parent] = self.heap[child]
            self.heap[child] = temp

            # Move the child and parent pointers up the heap
            child = parent
            parent = (child - 1) / 2

0 个答案:

没有答案