Hello friends..!
I tried to implement HeapSort algorithm in Java. but I've got some problems. First I should say that I have tried to implement the algorithm mentioned in the book "Introduction to Algorithm". the first question is how we can maintain the heap size? The book doesn't help with that. I choose the 0th element of the array as the heap size.
but when I run the program it ended up with bunch of Arrayoutbound errors.. Can you help me out guys..?
thank you in advance.
class heapSort{
int getParent(int i){
return (int) Math.floor(i/2);
}
int getLeft(int i){
return 2*i;
}
int getRight(int i){
return 2*i+1;
}
void maxHeapify(int[] A,int i){
int l,r,largest;
l=this.getLeft(i);
r=this.getRight(i);
if(l<=A[0] && A[l]>A[i])
largest=l;
else
largest=i;
if(r<=A[0] && A[r]>A[largest])
largest=r;
if(largest!=i){
A=this.swap(A, A[i], A[largest]);
maxHeapify(A, i);
}
}
int[] swap(int[] A,int a,int b){
int temp;
temp=A[a];
A[a]=b;
A[b]=temp;
return A;
}
void buidMaxheap(int[] A){
A[0]=A.length;
for(int i=(int) Math.floor((A.length)/2);i>0;i--){
this.maxHeapify(A, i);
}
}
int[] heapSort(int[] A){
this.buidMaxheap(A);
for(int i=A.length;i>2;i--){
this.swap(A, A[1], A[i]);
A[0]--;
this.maxHeapify(A, 1);
}
return A;
}
}