数组超出阵列上的递归插入排序

时间:2013-11-01 04:10:12

标签: java arrays exception recursion

论坛的新手,只是有一个简单的问题。 我试图弄清楚如何递归地编写插入排序算法。 递归对我来说仍然很混乱。

当我运行我的程序时,我收到一个数组超出范围的异常,我想知道究竟是什么造成了这个以及为什么。

我正在插入25个整数:25 67 13 98 30 22 47 52 11 20 76 13 9 53 86 21 7 45 68 29 18 93 44 50 62。

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;


class ArrayIns {
private int[] a;
private int nElems;

public ArrayIns(int max) {
    a = new int[max];
    nElems = 0;
}

public void insert(int value) {
    a[nElems] = value;
    nElems++;
}

public void display() {
    for (int j = 0; j < nElems; j++) {
        System.out.print(a[j] + " "); 
    }
    System.out.println("");
}

public void insertionSort() {
    insertSortRecursive(nElems - 1);
}

private void insertSortRecursive(int index) {
    int i;
    if (index < 1) {
    } else {
        insertSortRecursive(index - 1);

        int key = a[index];
        i = index - 1;

        while(index >= 0 && a[i] > key) {
            a[i+1] = a[i];
            i = i - 1;
        } // while
    } // else
} // End of recursiveSort
} // ArrayIns

class InsertSortApp {
public static void main(String[] args) throws FileNotFoundException {
    int maxSize = 50;
    ArrayIns arr;
    arr = new ArrayIns(maxSize);

    Scanner inputFile;

    inputFile = new Scanner (new FileReader("int.dat"));

    while(inputFile.hasNext()) {
        int in = inputFile.nextInt();
        arr.insert(in);
    }

    arr.display();

    inputFile.close();
}
} // End of insertsortapp

1 个答案:

答案 0 :(得分:1)

你还没有调用sort函数,所以问题不在于你的递归算法。我认为它是在你的文件阅读器循环时,它添加了超过50“整数”。

最好打印一个计数器,看看它经过多少循环(省略插入来测试你的while循环)。

尝试:

inputFile = new Scanner (new FileReader("int.dat"));

while(inputFile.hasNextInt()) {
    int in = inputFile.nextInt();
    arr.insert(in);
}