实际完成排序时的heapsort算法澄清

时间:2015-06-24 16:38:42

标签: arrays algorithm sorting heapsort

我对heapsort以及涉及到的堆有一些疑问。

  1. 当你从一个数组构建meax-heap时,实际上你构建了一个独立的对象,或者你只是安排数组允许遵循算法来构建堆来构建一个最大堆?

  2. 按照表示最大堆的顺序重新排列数组后,您希望对该数组进行排序或生成从该数组的元素排序的另一个数组。

  3. 这样做的算法是:

    A - 是一个数组示例:{5,3,17,10,19,84,6,22,9}

    堆排序(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);
    }
    

    从我的角度来看,它似乎实际上创建了一个数组A大小的堆(实际上是一个最大堆)。 然后在实际完成迭代的过程中,显然是在数组和MAX-HEAPIFY上 - 现在以某种方式在一个尖叫的堆上。

    你能一步一步地澄清这些事情吗?

1 个答案:

答案 0 :(得分:0)

之后,花了一些时间在搜索上我找到了为什么有一个堆大小,还有一个array.length(该数组实际上是表示堆的对象)。 如果你不希望实际上在数组尾部有更多的空闲点,当你在堆中添加一个元素时,你将只增加1个点的数组大小,那么你实际上并不需要堆大小,因为它们将始终相同,即array.length。

但是,如果你这样做,那将是数组上堆的简单实现,因为每次向堆/数组添加或删除/提取元素时,该操作的成本将为O (n)因为您将被迫将旧数组的值复制到新数组中。

但是当我们删除/提取一个节点时,我们实际上并没有缩小数组,删除操作会花费我们最大/最小堆O(log n),为什么?

当我们从堆中删除item / node(实际上是root)时,我们只需执行以下操作: (为了简化我们将使用int的东西)

1 store the root in auxiliary variable: int returnObj = array[0]; cost O(1)
2 put the value from the last element of the heap(why not array because only the heap-size 
will decrease, the array length is the same) into the first 
heap/array element array[0]=array[heap-size-1]; heap-size at the beginning == array.length
2.1 right now we have have last element ==first element, 
and we need to shrink the heap represented on the array somehow. 
Now comes the reason to have a heap-size variable independent of array.length if we don't 
want to actually shrink the array because that operation will cost us O(n-1) time 
- instead of doing that we will use an auxiliary variable heap-size, 
as i mentioned above-to mark the end of the heap, to be able to ignore tail elements of the 
array that actually are not part of the heap any-more.
2.2 because right now the first element of the array and also is the first element of 
the heap is actually one of the smallest - i am saying is one of the smallest because 
it is not mandatory that the last element to be the smallest to satisfy  the heap property, 
example {84, 22, 17, 10, 19, 5, 6, 3, 9} is a max-heap - 
we need to call max-hipify over array[0] ... to ... array[heap-size] to recreate the max-heap 
again. That will cost us O(log n) in the worst case, much less than O(n).

3 return returnObj;