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 int[] reverse(int[] array) {
int j = array.length-1;
// swap the values at the left and right indices //////
for(int i=0; i<=j; i++)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
return array;
}
public static void main(String []args){
int[] data = {1,2,3,4,5,6,7,8,9};
reverse(data);
}
It is most efficient to simply iterate the array backwards.
I'm not sure if Aaron's solution does this vi this call Collections.reverse(list);
Does anyone know?
To reverse an int array, you swap items up until you reach the midpoint, like this:
for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
The way you are doing it, you swap each element twice, so the result is the same as the initial list.
This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.
I hope you glean something from it.
@Test
public void reverseTest(){
Integer[] ints = { 1, 2, 3, 4 };
Integer[] reversedInts = reverse(ints);
assert ints[0].equals(reversedInts[3]);
assert ints[1].equals(reversedInts[2]);
assert ints[2].equals(reversedInts[1]);
assert ints[3].equals(reversedInts[0]);
reverseInPlace(reversedInts);
assert ints[0].equals(reversedInts[0]);
}
@SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
if (array == null) {
return (T[]) new ArrayList<T>().toArray();
}
List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
Collections.reverse(copyOfArray);
return copyOfArray.toArray(array);
}
private static <T> T[] reverseInPlace(T[] array) {
if(array == null) {
// didn't want two unchecked suppressions
return reverse(array);
}
Collections.reverse(Arrays.asList(array));
return array;
}
2 ways to reverse an Array .
Using For loop and swap the elements till the mid point with time complexity of O(n/2).
private static void reverseArray() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
int index = array.length - i - 1;
array[i] = array[index];
array[index] = temp;
}
System.out.println(Arrays.toString(array));
}
Using built in function (Collections.reverse())
private static void reverseArrayUsingBuiltInFun() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
Collections.reverse(Ints.asList(array));
System.out.println(Arrays.toString(array));
}
Output : [6, 5, 4, 3, 2, 1]
public class ArrayHandle {
public static Object[] reverse(Object[] arr) {
List<Object> list = Arrays.asList(arr);
Collections.reverse(list);
return list.toArray();
}
}