0

我发布只是因为我遇到了我正在编写的代码的墙壁。

代码的目标是使用 selectionSort 方法中的 swap 和 IndexOMaxInRange 方法从最大到最小对数组进行排序。我知道我的代码可能很草率,但我真的遇到了这个问题。

我的问题是:

为什么我总是收到“解析时到达终点”错误,这可能很明显,但我不热衷于使用 return 语句,因此在尝试调试时可能会有所帮助,但我对此很迷茫。

我运行代码时得到的错误是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at indexofmaxinrange.IndexOfMaxInRange.selectionSort(IndexOfMaxInRange.java:27)
at indexofmaxinrange.IndexOfMaxInRange.main(IndexOfMaxInRange.java:36)
Java Result: 1

code:


package indexofmaxinrange;
import java.util.Arrays;
/**
* @author zrcenivi
*/

public class IndexOfMaxInRange {
public static int indexOfMaxInRange (int[]a){        
Arrays.sort(a);
int gindex = a.length - 1;
return gindex;
} 
public static int[] swapElement(int[]a2, int j, int i) {
int temp = i;
a2[i] = a2[j];
a2[j] = temp;
return a2;
}
public static int[] selectionSort(int[]a){
Arrays.sort(a);
int min=0; int temp;
for (int i=0;i<=a.length - 1;i++){
min = i;
}
for (int j = a.length; j >=0; j--){
if (a[min]<a[j]){
a = swapElement(a,a[min],a[j]);
}
}      
return a;
}
public static void main(String[] args) {
int[] A = {1,3,2};
System.out.println(selectionSort(A));
}
4

2 回答 2

1

尝试这个

for (int j = a.length - 1; j >=0; j--) {
}

代替

for (int j = a.length; j >=0; j--){
}

此外,这将打印您所期望的

public static void main(String[] args) {
  int[] A = { 1, 3, 2 };
  System.out.println(Arrays.toString(selectionSort(A)));
}
于 2013-11-13T05:01:08.787 回答
0

以下2个地方会导致Index Out of Range。

1 for (int **j = a.length**; j >=0; j--){

我们可以使用的最大索引a.length -1是. 你应该使用

for (int j = a.length-1; j >=0; j--){

2 您应该将索引传递给方法swapElement,而不是带有索引的数组中的值。这是因为该值可能超过 Array 的长度。

 if (a[min]<a[j]){

  a = swapElement(a,a[min],a[j]);
 }

请改用以下代码。

 if (a[min] < a[j]) {
            a = swapElement(a, min, j);
        }

此外。您可以使用Arrays.toString方法打印数组内容。

 System.out.println(Arrays.toString(selectionSort(A)));

文本示例如下:

int[] A = { 1, 3, 2, 4, 9, 25,12};
System.out.println(Arrays.toString(selectionSort(A)));

控制台输出:

[1, 2, 3, 4, 9, 12, 25]
于 2013-11-13T05:08:35.467 回答