0

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
1
  • 1
    When you post questions like this about the exception, it helps us a lot if you put in things like the stack trace (trim out the useless bits), or the line of the error with the title/message from the exception. Commented Nov 1, 2013 at 4:34

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.