java - Getting error in implementation of heap sort -
i'm trying create , sort heap using array in java. keep getting
exception in thread "main" java.lang.arrayindexoutofboundsexception: 42
@ heapsort.exchange(heapsort.java:28)
@ heapsort.max_heapify(heapsort.java:22)
@ heapsort.build_heap @ heapsort.sort(heapsort.java:36)
@ heapsort.main(heapsort.java:46)
i'm not sure error coming from.
public class heapsort { public static int n; public static int[] a; public static int largest; public static void build_heap(int[] a){ n = a.length-1; for(int = n/2; >= 0; i--){ max_heapify(a,i); } } public static void max_heapify(int[] a,int i){ int left = 2*i; int right = 2*i +1; if(left <= n && a[left] > a[i]) largest = left; if(right <=n && a[right] > a[largest]) largest = right; if(largest != i) exchange (a[i],a[largest]); max_heapify(a,largest); } private static void exchange(int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; // todo auto-generated method stub } public static void sort(int[] a0){ = a0; build_heap(a); for(int = n; > 0; i--){ exchange(0,i); n = n-1; max_heapify(a,0); } } public static void main(string[] args){ int[] a1 = {3,55,6,42,34,56,34}; sort(a1); for(int = 0; < a1.length; i++){ system.out.print(a1[i] + " "); } } }
you getting error in exchange()
. parameters i
, j
method indexes of array a
. but, calling method exchange(a[i],a[largest])
passing value of array @ indexes i
, largest
instead of passing actual indexes i
, largest
method.
try calling exchange exchange(i,largest)
Comments
Post a Comment