was wondering if i could get some quick help with a heapsort implementation. I have it working and sorting fine but in the output it is always everything is sorted except the first number. It’s probably just a check somewhere but i have gone over my code and tried changing values but nothing produced the results i needed. Any advice to where i went wrong?
here is my source code:
code removed, problem was solved!
thanks guys!
I have fixed your bug and tested it on my machine. It should work. Just a couple minor changes in these two methods.
To summarize what you didn’t get right:
In
heapsortmethod, thecountyou passed in is zero-based index. However, when you built the heap you only looped tok = 1, i.e., one more iteration to go.In
movedownmethod, you should have known the left child index is2*k+1while the right child index is2*k+2.That you didn’t keep consistent with your indexing choices(i.e., 0-based vs. 1-based) resulted in the bug I guess.