Search code examples
javasortingheapsort

heapsort working 99%


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!


Solution

  • private static void movedown(double [] a, int k, int c) {
        while (2*k <= c-1) {
            int j = 2*k+1;
            if (j <= c-1 && less(a[j], a[j+1])) j++;
            if (!less(a[k], a[j])) break;
            exch(a, k, j);
            k = j;
        }
    }
    
    public static void heapsort(double [] a, int count) {
        for (int k = count/2; k >= 0; k--)
            movedown(a, k, count);
        while (count >= 1) {
            exch(a, 0, count--);
            movedown(a, 0, count);
        }
    }
    

    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:

    1. In heapsort method, the count you passed in is zero-based index. However, when you built the heap you only looped to k = 1, i.e., one more iteration to go.

    2. In movedown method, you should have known the left child index is 2*k+1 while the right child index is 2*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.