簡體   English   中英

堆排序-ArrayIndexOutOfBoundsException -java

[英]Heap sort - ArrayIndexOutOfBoundsException -java

我試圖做一個堆排序類,但出現此錯誤

java.lang.ArrayIndexOutOfBoundsException

這是我的代碼

package heap_sort;

public class main {

    public static void main(String[] args) {
        int a[]={16,4,10,14,7,9,3,2,8,1};
        heapsort(a);

    }
public static void heapsort(int a[])
{
    build_max_heap(a);
    for(int i = a.length ;i<=2 ;i--)
    {
        a[1]=a[i];
        max_heapify(a,1,i-1);
    }

}
public static void build_max_heap(int a[])
{
    int n=a.length;
    for (int i =n/2 ;i>=1 ;i--)
    {
        max_heapify(a,i,n);
    }
}
public static void max_heapify(int a[],int i , int n)
{
    int L=i*2;
    int R=(i*2)+1;
    int Largest=i;
    if (L<=n && a[L] > a[i])

    Largest=L;


    if (R>=n && a[R]>a[Largest])
    {
        Largest=R;
    }
    if (Largest != i)
        Changing(a,i,Largest);
    max_heapify(a,Largest,n);
}
public static void Changing (int a[],int i,int LL)
{
    int T=a[i];
    a[i]=a[LL];
    a[LL]=T;
}
}

誰能告訴我我的問題是什么,我應該怎么解決?

您的代碼中的問題在於,它假定數組中的初始索引為1 ,而最后一個索引為a.length含) 例如:

for(int i = a.length ; i <= 2 ; i--)

這是不正確的。 Java數組下標從零開始,然后轉到a.length排他的 這行代碼應如下所示:

for(int i = a.length-1 ; i >= 1 ; i--)
// The condition is inverted, too: i <= 2 should be i >= 1

您在代碼中做出相同假設的其他位置需要進行如下修復:

for (int i = n/2 ; i>=1 ; i--)
// should be i >= 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM