Skip to content
Advertisement

swap each element with its neighbour element in an array

I need to write a program. This method will take integer array as input and return array where each value is swapped with its neighbour element. In case the array has odd count, then last element is not swapped.

int[] array ={111,77,88,44,32,11,13,25,44}

Result:

    finalarray= 77,111,44,88,11,32,25,13,44

I tried using nested for loops but didnt get it

public static int[] swap(int array[]) {
        for (int i = 1; i < array.length; i++) {
            for (int j = i; j <= i; j++) {
                int temp = array[i - 1];
                array[i - 1] = array[j];
                array[j] = temp;
            }

        }
        for (int k = 0; k < array.length; k++) {
            System.out.print(array[k] + " ");
        }

        //Desired output 17,111,44,88,11,32,25,13,44
        return array;
    }

    public static void main(String args[]) {
        int[] number = { 111, 17, 88, 44, 32, 11, 13, 25, 44 };
        number = swap(number);

    }

Advertisement

Answer

Where is the code you tried so far ?!

Anyway

for (int i = 0; i < array.length; i += 2) {
        if(i+1 >= array.length) {
            break;
        }
        int temp = array[i];
        array[i] = array[i+1];
        array[i+1] = temp;
    }
9 People found this is helpful
Advertisement