I have some question about heapsort and about the heap involved in that.
when you build the meax-heap from an array, actually you build that heap a standalone object, or you just arrange the array to allow following the algorithm to build the heap to construct from that a max-heap?
after you rearrange the array in the order that represents a a max-heap you want sort that array or produce another array sorted from the elements of that array.
The algorithm to do that is:
A -- is an array example: {5, 3, 17, 10, 19,84, 6, 22, 9}
HEAPSORT(A)
1 BUILD-MAX-HEAP(A)
// here you rearrange the array to represent a max heap or
you actually construct a maxheap from that?
//a max heap array representation will be:
{84, 22, 17, 10, 19, 5, 6, 3, 9}
2 for i = A.length downto 2{
3 exchange A[1] with A[i];
4 A.heap-size = A.heap-size - 1; -- what this do in fact?
5 MAX-HEAPIFY(A, 1);
}
From my point of view it seems to actually create a heap of array A size (a max-heap actually). Then on what is done actually the iteration, aparently is over the array and MAX-HEAPIFY - now on a shrieked heap somehow .
Can you clarify me with those things step by step?
After, some time spent on searching I found why there is a heap-size, and also an array.length (the array is actually the object where the heap is represented). If you don't want actually to have more free spots at the array tail and when you add an element in the heap you you will increase the array size with only 1 spot, then you don't actually need the heap-size, because they will be always identical, and that is array.length.
However if you do that, that will be a naive implementation of the heap over the array, because every time when you add, or delete/extract an element to/from the heap/array the cost of that operation will be O(n) because you will be forced to copy the values of the old array into the new array.
But when we remove/extract a node, we are not shrinking in fact the array, the operation of removing will cost us in a max/min heap O(log n), why?
when we remove item/node - actually the root - from the heap we just do the following: (to simplify thing we will use int)