Replacing elements in array by the larger of its neighbour

Discussion in 'Java' started by hawthorns, Oct 12, 2018.

  1. hawthorns


    Oct 12, 2018
    Likes Received:
    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;
    hawthorns, Oct 12, 2018
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.