Hi,
I tried implementing the Heapsort algorithm. Here is my code:
(I'm sorry for the worse looking. In Eclipse I have indented the code.)
The problem is, that an ArrayIndexoutofBoundsException occurs, but I can't find a solution for this problem.
Thanks for help!
public class Heapsort {
public static void reheap(int [] a, int m, int i) {
if(2*i<=m) { // a[i] has left son
int j = 2*i; // a[j] is left son of a[i]
if(j<m) {
if(a[j]<a[j+1]) {
j=j+1;
}
}
if(a[i]<a[j]) {
int buffer = a[i];
a[i] = a[j];
a[j] = buffer;
}
else { // heap is correct
j = m; // breaks
}
reheap(a,m,j);
}
}
public static void buildheap(int [] a, int n) {
for(int i = Math.floorDiv(n,2); i>=0; i--) {
reheap(a,n,i);
}
}
public static void Heapsort(int [] a, int n) {
buildheap(a,n);
for( i = 1; i<n; i++) {
int buffer = a[1]
a[1] = a[n+1-i];
a[n+1-i] = buffer;
reheap(a,n-1,1);
}
}
public static void main(String[] args) {
int [] a = new int[] {1,8,3,9,5,2,10,7,4};
Heapsort(a, a.length);
for(int i=0; i<a.length; i++) {
System.out.print(a[i]);
}
}
}