System.arraycopy returns arrayoutofboundsexception
I learned about the arraycopy () function in java today and I worked with it in code. But I kept getting ArrayOutOfBoundsException. I tried to find a solution and google for solutions, but I can't seem to solve it. It would be helpful if someone can have a look at it.
System.arraycopy(a, 0, b, 1, N + 1);
Here "a" is an array of length "N" and b is another array of length "N + 1", I want to copy all the elements of array "a" to array "b" in such a way that all elements of array "a" start with second index of array "b", leaving space for another element in array "b"
Here is all the code if it requires:
import java.util.Random;
import java.util.Scanner;
public class JavaApplication24 {
public static long DC;
public static long DM1;
public static long DM;
private static int[] Insrtn_sort(int[] a, int N) {
int t, i;
int b[] = new int[N + 1];
DC = 0;
DM = 0;
DM1 = 0;
b[0] = Integer.MIN_VALUE;
System.arraycopy(a, 0, b, 1, N + 1);
for (int j = 1; j < N + 1; j++) {
t = b[j];
i = j - 1;
while (t < b[i]) {
b[i + 1] = b[i];
i--;
DC++;
DM1++;
}
b[j + 1] = t;
DM++;
}
return b;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random r = new Random();
float StartTime, EndTime, TotalTime;
int N = sc.nextInt();
int[] a = new int[N];
for (int i = 0; i <= N - 1; i++) {
a[i] = r.nextInt();
}
StartTime = System.currentTimeMillis() / 1000;
Insrtn_sort(a, N);
EndTime = System.currentTimeMillis() / 1000;
TotalTime = StartTime - EndTime;
for (int i = 1; i <= N - 1; i++) {
System.out.println(a[i]);
}
System.out.println("Time taken for sorting: " + TotalTime);
System.out.println("Total number of data comparisons: " + DC);
System.out.println("Total number of data movements: " + DM + DM1);
}
}
+3
source to share
2 answers