tags:

views:

97

answers:

2

I have a problem with this algorithm for Heap-Sort

Heap_Sort(A)
  Build_Heap(A)
  for i<--n down to 2
    swap (A[1],A[n])
    n<--n-1
    MaxHeapify(A,1)

I think instead of this algorithm we should write:

Heap_Sort(A)
  Build_Heap(A)
  for i<-- n down to 1
    Delete_Max(A)
+1  A: 

If you move the max element to the back of your heap array and then delete it, you're not going to be left with anything in your array when completes. So, your algorithm, which deletes the max, is not going to result in a sorted array of your original elements.

Update based on OP edit:

You can do it that way. The first method, though, allows you to sort in place. Your method requires O(N) additional storage.

Another Edit:

It's difficult to see exactly what assumptions you're making on the first algorithm, but as I think about the comment I made below, it seems likely that MaxHeapify(A,1) should probably be MaxHeapify(A, n). You will usually pass an array and its size, or in this case, the number of elements you want to arrange as a heap. This might be moot if you are assuming that n is a global variable.

andand
sorry I have edited my post!I had a mistake
if I swap a[1] and a[n] so what will happen to the max value ?
@martin1234: The swap allows the algorithm to sort in place. The n<-n-1 simply says that the size of the heap has been reduced so that the max element you found doesn't get reinserted into the heap (i.e. it decrements the heap size).
andand
So the first algorithm is incorrect ?*Heap_Sort(A) Build_Heap(A) for i<--n down to 2 swap (A[1],A[n]) n<--n-1 MaxHeapify(A,1)*
@martin1234: The first algorith, seems to me to be a correct in-place heap sort depending on global variables and the like (I probably would have designed MaxHeapify to take A and n as arguments). Otherwise, the second one (based on your comments) is also correct, but it has the disadvantage that it requires additional O(N) storage. Of course that's implementation specific, and it could be implemented to shrink one container while growing the other but that could induce other performance issues.
andand
+1  A: 

If you're doing an in-place sort...

Heap_Sort(A)
    B = Build_Heap(A)    # Assuming maxheap

    for i -> A.length to 0:
        Remove top value from B (which is basically just A, but treated differently),
        assuming the heap is modified to maintain partial ordering during this part
        (as well as decreasing the noted size of the heap by 1) and add the removed
        value to position A[i].

Basically your algorithm. If you aren't doing the sort in place, though, you can simply use a minheap and pop all the values into a new array.

JAB
with your version I have problem with your version,I think there is a problem
@matin: Yes, I redid the algorithm. I made a few assumptions as to how the heap itself is supposed to work, though.
JAB