I am trying to reverse an int array in Java.
This method does not reverse the array.
for(int i = 0; i < validData.length; i++)
{
int temp =
public static void main(String args[]) {
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
private static void reverse(int[] arr, int length) {
for(int i=length;i>0;i--) {
System.out.println(arr[i-1]);
}
}
private static int[] reverse(int[] array){
int[] reversedArray = new int[array.length];
for(int i = 0; i < array.length; i++){
reversedArray[i] = array[array.length - i - 1];
}
return reversedArray;
}
for(int i=validData.length-1; i>=0; i--){
System.out.println(validData[i]);
}
Your program will work for only length = 0, 1
.
You can try :
int i = 0, j = validData.length-1 ;
while(i < j)
{
swap(validData, i++, j--); // code for swap not shown, but easy enough
}
I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
I also think it's more readable to do this in a while loop.
public static void reverse(int[] data) {
int left = 0;
int right = data.length - 1;
while( left < right ) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the left and right index pointers in toward the center
left++;
right--;
}
}
This will help you
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}