Java Program to swap adjacent elements of an array


In this program, You will learn how to swap adjacent elements of an array in Java.


List is: 1 2 3 4 5 6

Adjacent list is: 2 1 4 3 6 5


Example: How to swap adjacent elements of an array in Java

Run it Now
import java.util.Scanner;

class Main {
    public static void main(String args[]) {

        int i, t;
        int arr[] = new int[6];

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter 5 Numbers :");

        for (i = 0; i < 6; i++) {
            arr[i] = sc.nextInt();
        }

        i = 0;
        while (i < 6 - 1) {
            t = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = t;
            i = i + 2;
        }

        System.out.print("\nAfter Swap List is :");
        for (i = 0; i < 6; i++) {
            System.out.print(" " + arr[i]);
        }

    }
}

Output:

Enter 5 Numbers :1 2 3 4 5 6
After Swap List is : 2 1 4 3 6 5