0

i am trying to copy the secon half of an array in to another array but it constantly keeps showing me error.It shows this, Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 4 at Practice/practice.MergerSort.main(MergerSort.java:16) public static void main(String[] args) {

int[] a= {7,2,5,3,7,13,1,6};
            int l=a.length;
            int m=l/2;
            int L[] = new int[m];
            int[] R = new int[m];
            for(int i=m;i<a.length;i++) {
                R[i]=a[i];
                System.out.println(R[i]);
            }
            
        }
    
    }
Abra
  • 19,142
  • 7
  • 29
  • 41
  • Always tag your questions with the appropriate language tag; that will ensure the maximum number of users gets to see them. – Nick Oct 29 '20 at 05:42

2 Answers2

0
public static void main(String[] args) {
    int[] a= {7,2,5,3,7,13,1,6};
    int l=a.length;
    int m=l/2;
    int L[] = new int[4];
    int[] R = new int[4];
    (int i=m;i<a.length;i++) {
        R[i-m]=a[i];
        System.out.println(R[i-m]);
    }
    
}

}

0

This is happens because i equals to 4, and R.length equals to 4, so index 4 isn't exist. try this for loop:

for(int i=m;i<a.length;i++) {
       R[i - L.length]=a[i];
       System.out.println(R[i - L.length]);
}
Programmer
  • 803
  • 1
  • 6
  • 13