在堆排序

时间:2016-02-05 19:54:32

标签: java

我试图在Java中使用此数组创建和排序堆。我一直在

  

线程中的异常" main" java.lang.ArrayIndexOutOfBoundsException:42
  在HeapSort.exchange(HeapSort.java:28)
  在HeapSort.Max_Heapify(HeapSort.java:22)
  在HeapSort.Sort的HeapSort.Build_Heap(HeapSort.java:36)
  在HeapSort.main(HeapSort.java:46)

我不确定错误的来源。

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 i = n/2; i >= 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){
        a = a0;
        Build_Heap(a);

        for(int i = n; i > 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 i = 0; i < a1.length; i++){
            System.out.print(a1[i] + " ");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

您在exchange()收到错误消息。该方法的参数ij看起来像是数组a的索引。但是,您正在调用方法exchange(a[i],a[largest]),该方法在索引ilargest处传递数组的值,而不是传递实际索引i和{{1}方法。

尝试调用largest

之类的交换

答案 1 :(得分:0)

'wco'中的exchange调用(第22行)会在这些位置给出数组的值而不是位置(索引Max_Heapify()i )可以是任何东西,在这个例子中,42大于要排序的数组长度,