BlueDolphin
BlueDolphin

Reputation: 9765

In place heap sorting in java code?

I am trying some heapsorting in java for fun.

First, I create a max-heap. Then take the first element to variable max, move the last item from unarranged array to the heap top, and then push down.

I tried 21 elements, it works fine 70% of time, I am wondering whether anyone find the problem.

Thanks.

public class HeapSort extends Sort{
    public int sort(int arr[]) {
        for (int i = 1; i < arr.length; i++) {
            // add to heap
            int p = i;
            int pp = p /2 ;
            while (p > 0 && arr[pp] < arr[p]) {
                swap(arr, p, pp);
                p = pp;
                pp = p / 2;
            }

        }   

        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            int p = 0;
            int child1 = (p << 1) + 1;
            int child2 = (p << 1) + 2;

            while (child2 < i || child1 < i) {
                if (child1 >= i) {
                    if (arr[p] < arr[child2]) {
                        swap(arr, p, child2);
                        p = child2;
                    } else { 
                        break;
                    }
                } else if (child2 >= i) {
                    if (arr[p] < arr[child1]) {
                        swap(arr, p, child1);
                        p = child1;
                    } else {
                        break;
                    }
                } else {
                    int minIdx = arr[child1] < arr[child2] ? child1 : child2;
                    int maxIdx = child1 == minIdx ? child2 : child1;

                    if (arr[p] < arr[maxIdx]) {
                        swap(arr, p, maxIdx);
                        p = maxIdx;
                    } else {

                        break;

                    }
                }
                child1 = (p << 1) + 1;
                child2 = (p << 1) + 2;
            }

        }
        return 0;

    }
    void swap(int arr[], int idx1, int idx2) {
        int tmp = arr[idx1]; arr[idx1] = arr[idx2]; arr[idx2] = tmp;
    }
    public String toString() {
        return "HeapSort";
    }

}

Upvotes: 2

Views: 4905

Answers (1)

Robert Richter
Robert Richter

Reputation: 278

You're not building the heap correctly in the first step of heap-sort. You need to subtract one before dividing by two on zero based arrays.

public class HeapSort extends Sort{ 
   public int sort(int arr[]) { 
      for (int i = 1; i < arr.length; i++) { // add to heap 
         int p = i;
         // int pp = p /2 ;  <======= Problem!
         int pp = (p-1) / 2; 
         while (p > 0 && arr[pp] < arr[p]) { 
            swap(arr, p, pp); p = pp; 
            //  pp = p / 2; // <=====Problem!
            pp = (p-1) /2;

}

Upvotes: 2

Related Questions