Heapsort Algorithm using min-heap

前端 未结 3 1545
逝去的感伤
逝去的感伤 2021-02-09 13:04

When I implement heapsort using a min-heap it sorts the array from largest to smallest. Is this the desired output for a heapsort using

3条回答
  •  离开以前
    2021-02-09 13:31

    Order: Use max-heapify to sort in asceding order, min-heapify to sort in descending order.

    Sorting: Building the heap with min-heapify does not sort your array; it only enforces the (weaker) min-heap property, that is

    A[parent(i)] <= A[i]
    

    for every node i other than the root. After the heap is built, the root (leftmost position in the array) has the minimum element. Sorting then repeatedly moves elements from the root to the right and calls min-heapify on the root (bringing there the minimum of what remains), hence the descending order.

    The code you are posting appears correct at a glance but does not compile as is, so I cannot test. If your array appears sorted right after building the heap, it should be a coincidence. Try a larger test.

提交回复
热议问题