Swap Two Adjacent Elements in an Array: This Java program takes an input array containing integers and swaps adjacent elements to create a modified array. It achieves this by iterating through the array with a step size of 2 (i.e., taking every second element) and swapping the positions of each pair of adjacent elements.
Swap Two Adjacent Elements in an Array
package com.softwaretestingo.interviewprograms; public class InterviewPrograms33 { /* * Input array- {1,2,3,4,5} * Output array- {2,1,4,3,5} */ public static void main(String[] args) { int[] arr = {1,2,3,4,5}; int tmp=0; for(int i =1;i<arr.length;i+=2) { tmp=arr[i]; arr[i]=arr[i-1]; arr[i-1]=tmp; } for(int i:arr) System.out.print(i); } }
Output
21435
Alternative Way 1:
This Java program takes an input array containing integers and swaps adjacent elements to create a modified array. The program achieves this using a for loop and conditional statements to handle arrays of even and odd lengths.
package com.softwaretestingo.interviewprograms; import java.util.Arrays; public class InterviewPrograms33_1 { /* * Input array- {1,2,3,4,5} * Output array- {2,1,4,3,5} */ public static void main(String[] args) { int [] a = {1,2,3,4,5}; if ( a.length % 2 == 1 ) { for ( int i = 0 ; i<a.length-1; i=i+2) { int temp= a[i]; a[i]= a[i+1]; a[i+1]=temp; } } else if (a.length%2==0) { for (int i=0; i<a.length; i=i+2) { int temp= a[i]; a[i] = a[i+1]; a[i+1]= temp ; } } System.out.println(Arrays.toString(a)); } }
Output
[2, 1, 4, 3, 5]