Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

implementation of heap sort

3394d429-e8cb-4a1e-8876-6e8f66bc78d7Oct 12 2015 — edited Oct 12 2015

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]);

  }

  }

}

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 9 2015
Added on Oct 12 2015
1 comment
578 views