I'll give you a hint. Think in terms of the heap invariant rather than a strict "swap with the largest child" algorithm, which the second solution given does less efficiently (even though it's easier to visualize).
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>I'm interested to know why are you using that implementation when you're talking about children at 2*k+1 and 2*k+2?
The initial discussion is about the concept that's easiest to follow initially. A working traditional implementation is then given, followed by a simplification of the concept and implementation that's easier to wrap your head around (for me at least). The traditional implementation doesn't follow the concept exactly in favor of a more efficient algorithm that simply ensures a valid heap.
>I can say I know that it works
Of course it works. :) But do you understand how and why it works? That's the point of my hint, stop trying to fit the concept exactly (this implementation is different) and remember that heapsort always works provided you start with a valid heap.
You'll enjoy that "Ah ha!" moment, when it all starts to make sense. :)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>What do you think about this implementation Narue?
Looks okay to me.
>I'm surprised that no one else commented this.
I'm almost finished with my red black tree tutorial. I'll make some adjustments and clarifications on the sorting tutorial after I post that one.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>Can you tell me, when new edition of sorting tutorial is expected Narue?
Sometime in November, I would wager.
>Can anybode suggest any good book on algorithms in C, but not too hard for beginers?
Algorithms in C by Robert Sedgewick is great on theory and explanation. The code is godawful, but can be useful if you know not to copy it. ;) There really aren't any algorithm books that cater to beginners without being useless, so just look for something with "algorithms" or "data structures" in the name and grab it if you find it easier to understand. Rest assured that you will be getting several books on the subject. I probably have a dozen. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401