Hey guys. I'm currently stuck on this one assignment where I don't know if I got the instructions wrong, or if the code is as it should be. The instructions is:
Replace each element except the first and last by the larger of its two neighbors.
I've completed the code, but the one problem I have is that the last element is being replaced even though it shouldn't. It'd very nice if you could take a look at my code.
public static void replaceWithNeighbours(int[] array) {
for (int i = 1; i < array.length - 1; i++) {
int larger = array[i - 1];
if (larger < array[i + 1]) {
larger = array[i + 1];
}
array = larger;
}
}
Replace each element except the first and last by the larger of its two neighbors.
I've completed the code, but the one problem I have is that the last element is being replaced even though it shouldn't. It'd very nice if you could take a look at my code.
public static void replaceWithNeighbours(int[] array) {
for (int i = 1; i < array.length - 1; i++) {
int larger = array[i - 1];
if (larger < array[i + 1]) {
larger = array[i + 1];
}
array = larger;
}
}