刚接触论坛,有一个简单的问题。我试图弄清楚如何递归地编写插入排序算法。递归对我来说仍然很困惑。
当我运行我的程序时,我收到一个 Array out of bounds 异常,我想知道究竟是什么导致了这个以及为什么。
我正在插入 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