How do I reverse an int array in Java?
JavaArraysIdiomsJava Problem Overview
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 = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
What is wrong with it?
Java Solutions
Solution 1 - Java
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.
Solution 2 - Java
With Commons.Lang, you could simply use
ArrayUtils.reverse(int[] array)
Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.
Solution 3 - Java
Collections.reverse(Arrays.asList(yourArray));
java.util.Collections.reverse()
can reverse java.util.List
s and java.util.Arrays.asList()
returns a list that wraps the the specific array you pass to it, therefore yourArray
is reversed after the invocation of Collections.reverse()
.
The cost is just the creation of one List-object and no additional libraries are required.
A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.
Solution 4 - Java
public class ArrayHandle {
public static Object[] reverse(Object[] arr) {
List<Object> list = Arrays.asList(arr);
Collections.reverse(list);
return list.toArray();
}
}
Solution 5 - Java
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--;
}
}
Solution 6 - Java
There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:
int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
Solution 7 - Java
In case of Java 8 we can also use IntStream
to reverse the array of integers as:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]
Solution 8 - Java
With Guava:
Collections.reverse(Ints.asList(array));
Solution 9 - Java
for(int i=validData.length-1; i>=0; i--){
System.out.println(validData[i]);
}
Solution 10 - Java
Simple for loop!
for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
Solution 11 - Java
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;
}
Solution 12 - Java
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;
}
Solution 13 - Java
If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.
public static void reverseArray4(int[] array) {
int len = array.length;
for (int i = 0; i < len/2; i++) {
array[i] = array[i] ^ array[len - i - 1];
array[len - i - 1] = array[i] ^ array[len - i - 1];
array[i] = array[i] ^ array[len - i - 1];
}
}
Solution 14 - Java
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
}
Solution 15 - Java
There are two ways to have a solution for the problem:
1. Reverse an array in space.
Step 1. Swap the elements at the start and the end index.
Step 2. Increment the start index decrement the end index.
Step 3. Iterate Step 1 and Step 2 till start index < end index
For this, the time complexity will be O(n) and the space complexity will be O(1)
Sample code for reversing an array in space is like:
public static int[] reverseAnArrayInSpace(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
while(startIndex < endIndex) {
int temp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = temp;
startIndex++;
endIndex--;
}
return array;
}
2. Reverse an array using an auxiliary array.
Step 1. Create a new array of size equal to the given array.
Step 2. Insert elements to the new array starting from the start index, from the given array starting from end index.
For this, the time complexity will be O(n) and the space complexity will be O(n)
Sample code for reversing an array with auxiliary array is like:
public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
int[] reversedArray = new int[array.length];
for(int index = 0; index < array.length; index++) {
reversedArray[index] = array[array.length - index -1];
}
return reversedArray;
}
Also, we can use the Collections API from Java to do this.
The Collections API internally uses the same reverse in space approach.
Sample code for using the Collections API is like:
public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
List<Integer> arrayList = Arrays.asList(array);
Collections.reverse(arrayList);
return arrayList.toArray(array);
}
Solution 16 - Java
There are some great answers above, but this is how I did it:
public static int[] test(int[] arr) {
int[] output = arr.clone();
for (int i = arr.length - 1; i > -1; i--) {
output[i] = arr[arr.length - i - 1];
}
return output;
}
Solution 17 - Java
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?
Solution 18 - Java
public void getDSCSort(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;
}
}
Solution 19 - Java
Solution with o(n) time complexity and o(1) space complexity.
void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
Solution 20 - Java
public void display(){
String x[]=new String [5];
for(int i = 4 ; i > = 0 ; i-- ){//runs backwards
//i is the nums running backwards therefore its printing from
//highest element to the lowest(ie the back of the array to the front) as i decrements
System.out.println(x[i]);
}
}
Solution 21 - Java
Wouldn't doing it this way be much more unlikely for mistakes?
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] temp = new int[intArray.length];
for(int i = intArray.length - 1; i > -1; i --){
temp[intArray.length - i -1] = intArray[i];
}
intArray = temp;
Solution 22 - Java
Using the XOR solution to avoid the temp variable your code should look like
for(int i = 0; i < validData.length; i++){
validData[i] = validData[i] ^ validData[validData.length - i - 1];
validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
validData[i] = validData[i] ^ validData[validData.length - i - 1];
}
See this link for a better explanation:
<http://betterexplained.com/articles/swap-two-variables-using-xor/>
Solution 23 - Java
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]
Solution 24 - Java
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]);
}
}
Solution 25 - Java
below is the complete program to run in your machine.
public class ReverseArray {
public static void main(String[] args) {
int arr[] = new int[] { 10,20,30,50,70 };
System.out.println("reversing an array:");
for(int i = 0; i < arr.length / 2; i++){
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
For programs on matrix using arrays this will be the good source.Go through the link.
Solution 26 - Java
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;
}
Solution 27 - Java
Here is a simple implementation, to reverse array of any type, plus full/partial support.
import java.util.logging.Logger;
public final class ArrayReverser {
private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());
private ArrayReverser () {
}
public static <T> void reverse(T[] seed) {
reverse(seed, 0, seed.length);
}
public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
if (seed == null || seed.length == 0) {
LOGGER.warning("Nothing to rotate");
}
int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
int end = Math.min(seed.length, endIndexExclusive) - 1;
while (start < end) {
swap(seed, start, end);
start++;
end--;
}
}
private static <T> void swap(T[] seed, int start, int end) {
T temp = seed[start];
seed[start] = seed[end];
seed[end] = temp;
}
}
Here is the corresponding Unit Test
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class ArrayReverserTest {
private Integer[] seed;
@Before
public void doBeforeEachTestCase() {
this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}
@Test
public void wholeArrayReverse() {
ArrayReverser.<Integer>reverse(seed);
assertThat(seed[0], is(8));
}
@Test
public void partialArrayReverse() {
ArrayReverser.<Integer>reverse(seed, 1, 5);
assertThat(seed[1], is(5));
}
}
Solution 28 - Java
Here is what I've come up with:
// solution 1 - boiler plated
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];
int lastIdx = original.length -1;
int startIdx = 0;
for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
reverse[startIdx] = original[endIdx];
System.out.printf("reverse form: %s", Arrays.toString(reverse));
// solution 2 - abstracted
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);
Solution 29 - Java
static int[] reverseArray(int[] a) {
int ret[] = new int[a.length];
for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
ret[i] = a[j];
return ret;
}
Solution 30 - Java
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);
}
Solution 31 - Java
A implementation using generics for arrays of non primitive types.
//Reverse and get new Array -preferred
public static final <T> T[] reverse(final T[] array) {
final int len = array.length;
final T[] reverse = (T[]) Array.newInstance(array.getClass().getComponentType(), len);
for (int i = 0; i < len; i++) {
reverse[i] = array[len-(i+1)];
}
return reverse;
}
//Reverse existing array - don't have to return it
public static final <T> T[] reverseExisting(final T[] array) {
final int len = array.length;
for (int i = 0; i < len/2; i++) {
final T temp = array[i];
array[i] = array[len-(i+1)];
array[len-(i+1)] = temp;
}
return array;
}
Solution 32 - Java
Solution 33 - Java
A short way to reverse without additional libraries, imports, or static references.
int[] a = {1,2,3,4,5,6,7,23,9}, b; //compound declaration
var j = a.length;
b = new int[j];
for (var i : a)
b[--j] = i; //--j so you don't have to subtract 1 from j. Otherwise you would get ArrayIndexOutOfBoundsException;
System.out.println(Arrays.toString(b));
Of course if you actually need a
to be the reversed array just use
a = b; //after the loop
Solution 34 - Java
Here is a condensed version:
> My solution creates a new array reversed > With each iteration of i the for loop inserts the last index [array.length - 1] into the current index [i] > Then continues the same process by subtracting the current iteration array[(array.length - 1) - i] from the last index and inserting the element into the next index of the reverse array!
private static void reverse(int[] array) {
int[] reversed = new int[array.length];
for (int i = 0; i < array.length; i++) {
reversed[i] = array[(array.length - 1) - i];
}
System.out.println(Arrays.toString(reversed));
}
Solution 35 - Java
Just for the sake of it. People often do only need a 'view' on an array or list in reversed order instead of a completely do not need a reversed array when working with streams and collections but a 'reversed' view on the original array/collection. , it is best to create a toolkit that has a reverse view on a list / array.
So create your Iterator
/// Reverse Iterator
public class ReverseIterator<T> implements Iterator<T> {
private int index;
private final List<T> list;
public ReverseIterator(List<T> list) {
this.list = list;
this.index = list.size() - 1;
}
public boolean hasNext() {
return index >= 0 ? true : false;
}
public T next() {
if(index >= 0)
return list.get(index--);
else
throw new NoSuchElementException();
}
}
An implementation for the array situation is quite similar. Of cause an iterator can be source for a stream or a collection as well.
So not always it is best to create a new array just to provide a reverse view when all you want to do is iterating over the array / list or feed it into a stream or a new collection / array.
Solution 36 - Java
This has 2 solution
-
Loop
-
Recursion
public class _1_ReverseArray {
public static void main(String[] args) { int array[] = {2, 3, 1, 4, 9}; //reverseArray(array, 0, array.length - 1); reverseArrayWhileLoop(array, 0, array.length - 1); printArray(array); } private static void printArray(int[] array) { for (int a : array) { System.out.println(a); } } private static void reverseArray(int[] array, int start, int end) { if (start > end) { return; } else { int temp; temp = array[start]; array[start] = array[end]; array[end] = temp; reverseArray(array, start + 1, end - 1); } } private static void reverseArrayWhileLoop(int[] array, int start, int end) { while (start < end) { int temp; temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } }
}
Solution 37 - Java
Simple way to do this:
for(int i=queue.length-1;i>=0;i--){
System.out.print(queue[i] + " ");
}
Solution 38 - Java
public static void main (String args[]){
//create array
String[] stuff ={"eggs","lasers","hats","pie","apples"};
//print out array
for(String x :stuff)
System.out.printf("%s ", x);
System.out.println();
//print out array in reverse order
for(int i=stuff.length-1; i >= 0; i--)
System.out.printf("%s ",stuff[i]);
}
Solution 39 - Java
public class TryReverse {
public static void main(String[] args) {
int [] array = {2,3,4,5,6,7,8,9};
reverse(array);
for(int i=0; i<array.length; ++i)
System.out.print(array[i] + " ");
}
public static void reverse (int [] array){
for(int start=0, end=array.length-1; start<=end; start++, end--){
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
}
}
Solution 40 - Java
Try this program in JAVA :-
import java.util.Scanner;
public class Rev_one_D {
static int row;
static int[] trans_arr = new int[row];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
row = n;
int[] arr = new int[row];
for (int i = 0; i < row; i++) {
arr[i] = sc.nextInt();
System.out.print(arr[i] + " ");
System.out.println();
}
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for (int i = 0; i < row; i++) {
System.out.print(arr[i] + " ");
System.out.println();
}
}
}
Solution 41 - Java
Here's a simple an quick solution. Hope it helps!.
public int[] reverse(int[] arr) {
for(int i = arr.length; i > 0 ; i--){
System.out.print(arr[i-1] + " ");
}
return arr;
}
Solution 42 - Java
Another way to reverse array
public static int []reversing(int[] array){
int arraysize = array.length;
int[] reverse = new int [arraysize+1];
for(int i=1; i <= arraysize ; i++){
int dec= arraysize -i;
reverse[i] = array[dec];
}
return reverse;
}
Solution 43 - Java
As I intended to keep my original Array as it was, I solved this problem in the following manner:
List<Integer> normalArray= new ArrayList<>();
List<Integer> reversedArray = new ArrayList<>();
// Fill up array here
for (int i = 1; i <= normalArray.size(); i++) {
reversedArray .add(normalArray.get(normalArray.size()-i));
}
So basically loop through the initial array and add all the values in reversed order to the new (reversed) array. The type of the list can be anything. I work my way through this code multiple times, this causes some of the other solutions not to work.
Solution 44 - Java
import java.util.Scanner;
class ReverseArray
{
public static void main(String[] args)
{
int[] arra = new int[10];
Scanner sc = new Scanner(System.in);
System.out.println("Enter Array Elements : ");
for(int i = 0 ; i <arra.length;i++)
{
arra[i] = sc.nextInt();
}
System.out.println("Printing Array : ");
for(int i = 0; i <arra.length;i++)
{
System.out.print(arra[i] + " ");
}
System.out.println();
System.out.println("Printing Reverse Array : ");
for(int i = arra.length-1; i >=0;i--)
{
System.out.print(arra[i] + " ");
}
}
}
Solution 45 - Java
You can use this
public final class ReverseComparator<T extends Comparable<T>> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
return o2.compareTo(o1);
}
}
An simply
Integer[] a = {1,6,23,4,6,8,2}
Arrays.sort(a, new ReverseComparator<Integer>());
Solution 46 - Java
Try this code:
int arr[] = new int[]{1,2,3,4,5,6,7};
for(int i=0;i<arr.length/2;i++){
int temp = arr[i];
arr[i] = arr[(arr.length-1)-i];
arr[(arr.length-1)-i] = temp;
}
System.out.println(Arrays.toString(arr));
Solution 47 - Java
int[] arrTwo = {5, 8, 18, 6, 20, 50, 6};
for (int i = arrTwo.length-1; i > 0; i--)
{
System.out.print(arrTwo[i] + " ");
}