An intuitive understanding of heapsort?

后端 未结 7 2133
春和景丽
春和景丽 2021-01-30 00:18

At school we are currently learning sorting algorithms in Java and I got for my homework the Heap Sort. I did my reading, I tried to find out as much as I could, but it seems I

7条回答
  •  面向向阳花
    2021-01-30 00:38

    I'll see how I go in answering this, because my explanation for heap sort and what a heap is will be a little...

    ...uh, terrible.

    Anyway, firstly, we'd better check what a Heap is:

    As taken from Wikipedia, a heap is:

    In computer science, a heap is a specialized tree-based data structure that satisfies the heap property: if B is a child node of A, then key(A) ≥ key(B). This implies that an element with the greatest key is always in the root node, and so such a heap is sometimes called a max-heap. (Alternatively, if the comparison is reversed, the smallest element is always in the root node, which results in a min-heap.)

    Pretty much, a heap is a binary tree such that all the children of any node are smaller than that node.

    Now, heap sort is an O(n lg(n)) sorting algorithm. You can read a little about it here and here. It pretty much works by putting all the elements of whatever you're trying to sort into a heap, then building the sorted array from the largest element to the smallest. You'll keep on restructuring the heap, and since the largest element is at the top (root) of the heap at all times, you can just keep taking that element and putting it at the back of the sorted array. (That is, you'll build the sorted array in reverse)

    Why is this algorithm O(n lg(n))? Because all the operations on a heap are O(lg(n)) and as a result, you'll do n operations, resulting in a total running time of O(n lg(n)).

    I hope my terrible rant helped you! It's a little bit wordy; sorry about that...

提交回复
热议问题