gpt4 book ai didi

java - 执行堆排序时出现错误

转载 作者:行者123 更新时间:2023-12-02 12:57:53 25 4
gpt4 key购买 nike

我正在尝试在 Java 中使用此数组创建堆并对其进行排序。我不断得到

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 42
at HeapSort.exchange(HeapSort.java:28)
at HeapSort.Max_Heapify(HeapSort.java:22)
at HeapSort.Build_Heap at HeapSort.Sort(HeapSort.java:36)
at 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] + " ");
}
}
}

最佳答案

您在 exchange() 中遇到错误。该方法的参数 ij 看起来像是数组 a 的索引。但是,您正在调用方法 exchange(a[i],a[largest]) ,该方法正在传递数组中索引 ilargest 处的值 而不是将实际索引 ilargest 传递给该方法。

尝试像 exchange(i,largest) 那样调用交换

关于java - 执行堆排序时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35232416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com