Beispiel #1
0
def heap_extract_max(heap):
    """
    :description: remove and return the max value while maintaining the max heap property

    :time: O(lgn)
    """
    assert len(heap) > 0

    heap[0], heap[-1] = heap[-1], heap[0]
    max_value = heap.pop()
    heap_ops.max_heapify(heap, 0)
    return max_value
Beispiel #2
0
def heap_extract_max(heap):
    """
    :description: remove and return the max value while maintaining the max heap property

    :time: O(lgn)
    """
    assert len(heap) > 0

    heap[0], heap[-1] = heap[-1], heap[0]
    max_value = heap.pop()
    heap_ops.max_heapify(heap, 0)
    return max_value
Beispiel #3
0
def heapsort(arr):
    """
    :description: heapsort, version not in place b/c the heap ops don't take heap size parameter. Works by removing largest element and calling max_heapify

    :time: O(nlgn) worst case calls max_heapify n times

    :space: O(n)
    """
    heap = arr
    heap_ops.build_max_heap(heap)
    sorted_arr = []
    for i in range(len(arr) - 1):
        heap[0], heap[-1] = heap[-1], heap[0]
        sorted_arr.append(heap.pop())
        heap_ops.max_heapify(heap, 0)
    sorted_arr.append(heap.pop())
    return list(reversed(sorted_arr))
Beispiel #4
0
def heapsort(arr):
    """
    :description: heapsort, version not in place b/c the heap ops don't take heap size parameter. Works by removing largest element and calling max_heapify

    :time: O(nlgn) worst case calls max_heapify n times

    :space: O(n)
    """
    heap = arr
    heap_ops.build_max_heap(heap)
    sorted_arr = []
    for i in range(len(arr) - 1):
        heap[0], heap[-1] = heap[-1], heap[0]
        sorted_arr.append(heap.pop())
        heap_ops.max_heapify(heap, 0)
    sorted_arr.append(heap.pop())
    return list(reversed(sorted_arr))