0

can someone please review this and tell me what is the problem ? cant i pass a reference to an array
to a constructor or what ? thanks ...

class Sort {
  int[] input ;
  int key=0;
  Sort(int[] k){
    //Sometimes a method will need to refer to the object that invoked it.
    this.input= k ;
  }
  int[] returnArray() {
    for(int i=2 ; i<=input.length ; i++){
      key=input[i];
      int j=i-1;
      while (j>0 && input[j]>key){
        input[j+1]=input[j];
        j-=1;
      }
      input[j+1]=key;
    }
    return input ;
  }
}
class InsertionSort{
  public static void main (String[] args){
    int[] A = {5,8,99,52,22,14,15,1,25,15585,36,244,8,99,25,8};
    Sort sort = new Sort(A);
    int[] B = sort.returnArray();
    for (int i=0 ; i<B.length ; i++){
      System.out.println("the array after sorting : ");
      System.out.print( B[i] + " " );
    }
  }
}

...
and this is the exact contents of the whatsitssname :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 16 out of bounds for length 16<br/>
at Sort.returnArray(InsertionSort.java:10)<br/>
at InsertionSort.main(InsertionSort.java:25)<br/>
Aditya Kurkure
  • 422
  • 5
  • 19
  • An array of length 16 starts at index 0 and ends at index 15. Your loop condition is wrong, instead of `i<=input.length` you should use `i < input.length`. Likely your initialization step with `i=2` is wrong as well. – Mark Rotteveel May 20 '20 at 15:56

2 Answers2

1

Your code is trying to access index 16 of the array, but the last index of that array is 15, because it has 16 elements starting at index 0.

This is where the problem happens:

for(int i=2 ; i<=input.length ; i++){
  // when i is input.length (16), you'll be accessing an out of bounds index
  // wich will throw a java.lang.ArrayIndexOutOfBoundsException
  key=input[i];

Since i should not reach input.length, you'll want to use < instead of <=.

rid
  • 61,078
  • 31
  • 152
  • 193
0

The error is in your for loop. It should be if you want to iterate from the 3rd element to the last.

 for(int i=2 ; i<input.length ; i++){

If you want to iterate from the 2nd element to the last one if should be

for(int i=1 ; i<input.length ; i++){

What you are doing now is basically trying to access i[len] for an array whose length is len. Which does not exist

Aditya Kurkure
  • 422
  • 5
  • 19