I've been trying to take a pre-made array of 100 random integers and reverse it. I'm not getting any error messages, but the resulting array is only reversed about halfway before it restarts. This has been messing up the results and I can't seem to find out what's wrong with it. I'm pretty new to Java so I have the feeling it's a simple mistake that I haven't found yet, so I'd appreciate any help or advice. For reference here's the method I created:
//create a method to reverse the array
public static void makeNewArray(){
System.out.println("\nReversed Array:\n");
//use a for loop to traverse the array
for(int i=numArray.length-1;i>=0;i--){
int temp = numArray[i];
numArray[i] = numArray[numArray.length - i - 1];
numArray[numArray.length - i - 1] = temp;
//print the reversed array
System.out.print("index " + (i+1) + ": "+ numArray[i] + ", ");
}
}
In the for-loop you are flipping the first number and the last number, the second number and the second-to-last number, the third number and the third-to-last number, and so on. If you go from start to the end you will flip each number twice, because you move fully though the array, and flip two numbers, therefore flipping twice the numbers in the array. You must only traverse half the array, ex:
int counter = 0;
for(int i = numArray.length-1; i >= counter; i--){
int temp = numArray[i];
numArray[i] = numArray[numArray.length - i - 1];
numArray[numArray.length - i - 1] = temp;
//print the reversed array
//System.out.print("index " + (i) + ": "+ numArray[i] + ", ");
counter++;
}
//print arr
// must be separate because must iterate the whole array
for(int i = 0; i < numArray.length; ++i){
System.out.print("Index: "+i+": "+numArray[i]+", ");
}
System.out.println(""); // end code with newline