What is the difference between A.length and A.heap-size?

你说的曾经没有我的故事 提交于 2020-01-03 06:58:09

问题


I have a question about heap sort. It state in an Algorithms book that A.heap-size<= A.length I don’t understand the difference between the two. If an array represents a heap, why is there a possibility that A.heap-size is less than A.length. I know that A.heap-size represents the number of elements inside a heap, so why is it not completely only equal to the number of items inside an array?


回答1:


The invariant of heap sort is that the first k elements of the n-element array are a heap on the k smallest elements, and the last n - k elements are the n - k largest elements in sorted order. The latter elements are why the heap does not occupy the whole array.




回答2:


Just to expand an answer. Read further that book.

A.heap_size of an array, is that place where heap (max_heap or min_heap) structure elements will be placed. It makes sense in scope of sorting or queuing. You are right: this is the number of elements inside a heap, but it's equal to A.length only at first iteration of heap sort.

At next iteration, after exchanging root of the max_heap tree (A[1]) with A[i] = A[A.length] (last element inside array A), the A[1] element will be the last element of the A, and A.heap_sort value will be decreased by 1 and max_heap structure should be max_heapified: A[Parent(i)] >= A[i], where Parent(i) returns i/2 of heap tree.




回答3:


From Cormen's Algorithm textbook which I'm using: (this helped me)




回答4:


A.length gives the total no of elements of array whereas A.heap size given the no of elements which are in sorted order or no of elements which are following the heap property........And A.length-A.heap size or even not sorted even now and has to be sort in future.



来源:https://stackoverflow.com/questions/19059806/what-is-the-difference-between-a-length-and-a-heap-size

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!