简体   繁体   中英

Max Heapify algorithm results

I've been playing around with some of the Algorithms in the Intro to Algorithms textbook, in specific I'm trying get a Binary Heap to work 100% correctly. I have a curious feeling that the example that I'm working with isn't correct, and I was wondering if anyone can help point me in the right direction.

Given the array

int[ ] arr = { 1, 2, 3, 4, 7, 8, 9, 10, 14, 16 };

The result I get from MaxHeapify is

[ 16, 14, 9, 10, 7, 8, 3, 1, 4, 2 ]

However, after doing a few Google searches, I found that people who use this exact array as an example expect the result to be:

[ 16, 14, 10, 8, 7, 9, 3, 2, 4, 1 ]

What confuses me is that the result that my MaxHeapify method gives satisfies the Heap property, but it's different than what is expected. Below is my implementation in Java

public static void BuildMaxHeap( int[ ] arr )
{
    for( int i = (int)Math.floor( arr.length - 1 ); i >= 0; i-- )
        MaxHeapify( arr, i );
}
public static void MaxHeapify( int[ ] arr, int i )
{
    int left = 2 * i + 1;
    int right = 2 * i + 2;
    int largest = i;

    if( left < arr.length && arr[ left ] > arr[ largest ] )
        largest = left;
    if( right < arr.length && arr[ right ] > arr[ largest ] )
        largest = right;
    if( largest != i )
    {
        int temp = arr[ i ];
        arr[ i ] = arr[ largest ];
        arr[ largest ] = temp;
        MaxHeapify( arr, largest );
    }
}

The heaps that you've shown are both valid. There's nothing to worry about.

There are multiple ways to order subnodes.

Consider the simplest case of swapping left with right:

   14         14
 10  9   vs  9  10
...  ...   ...  ...

Your heaps are valid. They are different because the array is not necessarily sorted when you apply neither of these methods. That's what Heapsort is for. Just one detail, in your BuildMaxHeap you may want to change

for( int i = (int)Math.floor( arr.length - 1 ); i >= 0; i-- )

to

for( int i = arr.length / 2; i >= 0; i-- )

The reason I say this is because you can start from the last node that has leaves as it's children, since leaves are always a max_heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM