This is the first solution to reverse all the numbers. This solution modifies the same array. The resultant array has all the numbers reversed.
public class ReverseAnArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Initialized the array values, and initialize the start Index to default 0
int [] numArray= {21,98,42,59,79,65,32};
int startIdx= 0, rearIdx;
System.out.println("Array values - Before reversing numbers");
dispArray(numArray);
//Calculate the rear Index position in the array based on the array length
rearIdx= numArray.length-1;
/*Start swapping the numbers at first and last positions of the array,
do continue swapping numbers by increasing first index to the next higher
index, and by decreasing last index to next lower index, until
those positions cross each or have same value*/
while (startIdx<=rearIdx) {
int tempNum=numArray[startIdx];
numArray[startIdx]=numArray[rearIdx];
numArray[rearIdx]=tempNum;
startIdx += 1;
rearIdx -= 1;
}
System.out.println("Array values - After Reversing Numbers at all 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
[ 21 98 42 59 79 65 32 ]
Array values - After Reversing Numbers at all positions
[ 32 65 79 59 42 98 21 ]

Leave a comment