views:

110

answers:

4

I have an operation on a heap, a fixdown operation . This is the code:

public class Heap {

    public static void fixdown (int a[],int k,int n) {
        while (2*k<=n) {
            int j=2*k;
            if (j<n && a[j]<a[j+1]) j++;
            if (!(a[k]<a[j])) break;
            swap(a,k,j);
            k=j; 
        }
    }

    public  static void main (String[]args) {
        int a[]=new int[]{12,15,20,29,23,22,17,40,26,35,19,51};
        fixdown(a,1,a.length);
        for (int i=0;i<a.length;i++) {
            System.out.println(a[i]);
        }
    }

    public static void swap (int a[],int i,int j) {
        int t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}

Update: I have changed it and now there is no error.

//result is

12
29
20
40
23
22
17
15
26
35
19
51
+1  A: 

a[j]=k;

You probably want:

a[j]=t;


On array declarations

Please, please, do not make a habit of declaring arrays like this:

int x[];

You should instead put the brackets with the type, rather than with the identifier:

int[] x;

Related questions

polygenelubricants
There are other problems too, I think. 2k <= n, j = 2k and he accesses a[j]...
Moron
what will be solution?
polygenelubricants please look at my output i am sure it is correct but can u advise me or check?
@polyg re: arrays - While I personally use `type[] ident;` for my declarations, and I do see where it is cited that it is "convention", would you care to elaborate on the rationale behind it? I happened to have picked it up the "right way", but I don't see a logical reason why it would be discouraged.
glowcoder
+1  A: 

you have a[j]=k;

perhaps it should be a[j]=t;

glowcoder
+1  A: 

The code is very hard to read in its current state of indentation, but I believe a[j]=k; should be a[j]=t;.

A: 

Those lines:

for (int i=0;i<a.length;i++){
 System.out.println(a[i]);

suggest, that indexes in Your array are 0 based. If so, the indexes of the left and right child of the element at index i should be calculated as

leftchild_index = 2*i+1;
rightchild_index = 2*i+2; // rightchild_index = leftchild_index + 1

left child of a[0] is a[1] and the right one is a[2]

If parameter n is the length of an array containing the heap, You need to fix some conditions

while(2*k<=n){

should be changed to:

while(2*k + 1 < n){

and

int j=2*k;
    if (j<n && a[j]<a[j+1])   j++;

should be changed to

int j = 2 * k + 1;
    if (j < n - 1 && a[j] < a[j+1])   j++;

Otherwise You are accessing the array out of bounds.

Maciej Hehl
thanks Maciej Hehl thank u very much
You could also describe right as rightchild = leftchild + 1; ^^
Helper Method