Computer Science › Insertions
public static int[] doWork(int[] arr, int val,int index) {
int[] ret = new int[arr.length + 1];
for(int i = 0; i < index; i++) {
ret[i] = arr[i];
}
ret[index] = val;
for(int i = index + 1; i < ret.length; i++) {
ret[i] = arr[i - 1];
}
return ret;
}
Which of the following is a possible error in the first loop in code above?
I. The array arr
might be indexed out of bounds.
II. The array ret
might be indexed out of bounds.
III. A null pointer exception might occur.
True or False.
The worst case for insertion into an ArrayList is O(N).
public static int[] doWork(int[] arr, int val,int index) {
int[] ret = new int[arr.length + 1];
for(int i = 0; i < index; i++) {
ret[i] = arr[i];
}
ret[index] = val;
for(int i = index + 1; i < ret.length; i++) {
ret[i] = arr[i - 1];
}
return ret;
}
What does the code above perform?
int\[\] arr = {0,0,0,0,0,0,0,0,0,0};
int arrFill = 0;
int val;
// In here, n items are added. ArrFill is n. Presume that n <= 9
// The variable val now contains a new value to be added
Which of the following blocks of code push a new value into arr as though it were a stack?