1

I'm trying to learn heapsort. I follow the pseudocode instruction, however, my program doesn't work properly. I have already debugging for an hour now and couldn't find the bug. There are a couple of bug: first, the arraylist doesn't sort properly; and second, the arraylist seem to be sorting from max -> min, even though it is suppose to be from min -> max. Sorry for beginner question.

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        int n;
        Scanner input = new Scanner(System.in);
        ArrayList<Integer> intList = new ArrayList<Integer>();
        Random rand = new Random();
        int minMax = 7000;

        System.out.print("Input a positive integer: ");
        n = input.nextInt();
        for (int i = 0; i < n; i++) {
            intList.add(rand.nextInt(minMax * 2) - minMax);
        }
        System.out.println(intList);
        Heapsort(intList);
        System.out.println(intList);
    }

    // Heapsort
    public static void Heapsort(ArrayList<Integer> num) {
        build_MaxHeap(num);
        int n = num.size() - 1;
        for (int i = n; i > 0; i--) {
            swap(num, 0, i);
            n = n - 1;
            max_heapify(num, 0);
        }
    }

    // build max heap from arraylist
    public static void build_MaxHeap(ArrayList<Integer> num) {
        for (int i = (num.size() - 1) / 2; i >= 0; i--)
            max_heapify(num, i);
    }

    // max heapify
    public static void max_heapify(ArrayList<Integer> num, int i) {
        int left = 2 * i;
        int right = 2 * i + 1;
        int max = i;
        int n = num.size() - 1;
        if (left <= n && num.get(left) > num.get(i))
            max = left;
        if (right <= n && num.get(right) > num.get(max))
            max = right;

        if (max != i) {
            swap(num, i, max);
            max_heapify(num, max);
        }
    }

    // swap 2 numbers in arraylist
    public static void swap(ArrayList<Integer> num, int i, int j) {
        int temp = num.get(i);
        num.set(i, num.get(j));
        num.set(j, temp);
    }
}
tnw
  • 13,521
  • 15
  • 70
  • 111
Joe Jame
  • 11
  • 1
  • I am still looking right now. I am rereading the pseudocode and the explanation. A hint on where to focus would be. – Joe Jame Apr 27 '15 at 19:31
  • 1
    Instrument your code so that it outputs the state of the heap in a convenient form (write a function for this purpose). Run the program on a known example and spot where things go wrong. You can also write a function that automatically checks the "heap" condition where it is deemed to be true. –  Apr 27 '15 at 20:26
  • I was able to get your code working pretty easily, but I had to add a `size` parameter to `max_heapify()`. Also note that for zero-based arrays, you will want to use `int left = 2 * i + 1;` and `int right = 2 * i + 2;`. – Daniel Nugent Apr 27 '15 at 21:12

0 Answers0