This is the first solution to reverse all the numbers at even positions. This solution modifies the same array. The resultant array has all the numbers reversed only even positions.
public class ReverseEvenPosElements {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Initialized the array values, even Index to default 1
int [] numArray= {41,16,24,9,72,63,35,15};
int evenIdx= 1, rearEvenIdx;
System.out.println("Array values - Before reversing numbers at even positions");
dispArray(numArray);
//Calculate the rearEven Index position in the array based on the array length
if (numArray.length%2 == 0)
rearEvenIdx= numArray.length-1;
else
rearEvenIdx= numArray.length-2;
/*Start swapping the numbers at first and last even positions of the array,
do continue swapping numbers by increasing first even index to the next higher
even index, and by decreasing last even index to next lower even index, until
those even positions cross each or have same value*/
while (evenIdx<=rearEvenIdx) {
int tempNum=numArray[evenIdx];
numArray[evenIdx]=numArray[rearEvenIdx];
numArray[rearEvenIdx]=tempNum;
evenIdx += 2;
rearEvenIdx -= 2;
}
System.out.println("Array values - After Reversing Numbers at even positions");
dispArray(numArray);
}
// Function to display the array values in some specific format
private static void dispArray(int[] varArray) {
System.out.print("[ ");
for (int i=0;i<varArray.length;i++) {
System.out.print(varArray[i]+" ");
}
System.out.println("]");
}
}
Output:
Array values - Before reversing numbers at even positions
[ 41 16 24 9 72 63 35 15 ]
Array values - After Reversing Numbers at even positions
[ 41 15 24 63 72 9 35 16 ]

Leave a comment