I should write algorithm which gets the array of numbers and return array of values with odd indexes
Input = {-5, 590, 234, 985, 14, 68}
Expected Result = {590, 985, 68}
I have written algorithm like this, but it does not work.
public int[] oddInd(int[] array) {
if (array.length > 0) {
int i1 = 0;
for (int i = 1; i < array.length; i += 2) {
i1 = array[i];
}
return new int[]{i1};
}
return new int [0];
}
When i print the algorithm the output is [1]
Help me , please. What`s wrong with my code?
>Solution :
You need to recalculate the size of the result array and populate it properly:
public int[] oddInd(int[] array) {
int[] res = new int[array.length / 2];
for (int i = 0; i < res.length; i++) {
res[i] = array[2 * i + 1];
}
return res;
}