Reputation: 1
New to the forums, just have a quick question. I am trying to figure out how to write the insertion sort algorithm recursively. Recursion is still quite confusing to me.
When I run my program I receive an Array out of bounds exception and am wondering what exactly is causing this and why.
I am inserting 25 ints: 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
Upvotes: 0
Views: 210
Reputation: 2630
You are not calling the sort function yet, so the problem isn't with you recursion algorithm. I think it is with your file reader while loop, it is adding more than 50 "integers".
The best would be print out a counter to see how many loops it goes through (omit the insert to test your while loop).
Try:
inputFile = new Scanner (new FileReader("int.dat"));
while(inputFile.hasNextInt()) {
int in = inputFile.nextInt();
arr.insert(in);
}
Upvotes: 1