SRL Archive - General

[Java]Heaps!


JPHamlett

2013-04-11 19:14:28


public void subHeap(E[] args, int index, int size){
boolean swap = false;
int lChild = leftChild(index);
int rChild = rightChild(index);
Comparable obj = (Comparable) args[index];
Comparable rObj = (Comparable) args[rChild];
Comparable lObj = (Comparable) args[lChild];
int high;
if (obj.compareTo(rObj) < 0 || obj.compareTo(lObj) < 0){
swap = true;
if (rObj.compareTo(lObj) < 0){
high = lChild;
} else {high = rChild;}
E temp = args[index];
args[index] = args[high];
args[high] = temp;
}
if (swap){subHeap(args, index, size); }
}

public Heap (E[] args){
for (int i = args.length/2; i > 0; i--){
subHeap(args, i -1, args.length);
}
for (E i: args){
System.out.print(i + " ");
}
}


I cannot get this code to work

I get a partial heap

Original array: 2 6 3 5 0 10 -2
Result Array: 10 6 2 5 0 3 -2


Any help?

Brandon

2013-04-12 13:32:42

From: JPHamlett

I cannot get this code to work

I get a partial heap

Original array: 2 6 3 5 0 10 -2
Result Array: 10 6 2 5 0 3 -2


Any help?



Without knowing LeftChild And RightChild functions, there is no way to tell what goes wrong where..
Also, that last argument "size" is redundant :S Unused.

JPHamlett

2013-04-12 14:35:10

From: Brandon
Without knowing LeftChild And RightChild functions, there is no way to tell what goes wrong where..
Also, that last argument "size" is redundant :S Unused.



public int leftChild(int n){
return 2 * n + 1;
}

public int rightChild(int n){
return 2 * n + 2;
}

JPHamlett

2013-04-14 02:13:08

Bump @Method