Heapsort Algorithm using min-heap

前端 未结 3 1587
逝去的感伤
逝去的感伤 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:41

    I was just wondering about that very problem ( isn't Heap sort having an extra step at the end, the unnecessary swapping of elements. Just use min-heaps and let call min-heapify and get your work done).

    Regarding this way, we could have achieved O(logn) time which somewhat disqualifies the binary decision tree model - which says O(nlogn) is acceptable tightest upper bound on comparison sorting algorithms.

    The short answer is: heap data structure aren't binary search trees. A heap may guarantee ordering of elements in sorted top->bottom way, but a binary search tree guarantees they'll be ordered left to right as well. We were just mixing up binary trees and heaps.

    A min heap only guarantees ,

    Amin[Parent]<=A[either_of_the_children] // says nothing about ordering of children
    

    Here is a binary tree (although unbalanced and not sorted) :

    Binary tree

    And here is a Heap :

    min heap

    Hope you get my point. If still not, then think of it as, a min heap represented an array guarantees that parent is smaller than its child, but says nothing about are all children arranged in sorted order left to right? We'll still be performing min-heapify on each child of current root to be swapped.

提交回复
热议问题