Reputation: 3037
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?
Upvotes: 301
Views: 718438
Reputation: 1450
For Java 8+, you can use the following to reverse an int[]:
int[] validData = {1, 2, 3};
validData = Arrays.stream(validData)
.boxed()
.sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue)
.toArray();
After this, validData will contain {3, 2, 1}.
Upvotes: -2
Reputation: 4959
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();
Upvotes: 18
Reputation: 39536
Using the Google Guava library:
Collections.reverse(Ints.asList(array));
Upvotes: 15
Reputation: 1919
Simple way to do this:
for(int i=queue.length-1;i>=0;i--){
System.out.print(queue[i] + " ");
}
Upvotes: 0
Reputation: 418
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;
}
Upvotes: 2
Reputation: 661
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--;
}
}
}
Upvotes: 0
Reputation: 5513
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 implementation that takes an array or list and provide the input.
/// 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.
Upvotes: 0
Reputation: 41
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));
}
Upvotes: 0
Reputation: 81
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
Upvotes: 0
Reputation: 24157
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]
Upvotes: 13
Reputation: 2056
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;
}
Upvotes: 4
Reputation: 31
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]);
}
}
Upvotes: 2
Reputation: 1008
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;
}
Upvotes: 6
Reputation: 1030
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);
}
Upvotes: 1
Reputation: 123
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]
Upvotes: 2
Reputation: 129
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;
}
Upvotes: 1
Reputation: 2137
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);
}
Upvotes: 5
Reputation: 1421
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] + " ");
}
}
}
Upvotes: -1
Reputation: 4289
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);
Upvotes: 1
Reputation: 171
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--;
}
}
Upvotes: 3
Reputation: 406
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;
}
}
Upvotes: 3
Reputation: 57
int[] arrTwo = {5, 8, 18, 6, 20, 50, 6};
for (int i = arrTwo.length-1; i > 0; i--)
{
System.out.print(arrTwo[i] + " ");
}
Upvotes: -6
Reputation: 564
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.
Upvotes: -1
Reputation: 323
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;
}
Upvotes: 9
Reputation: 81721
public class ArrayHandle {
public static Object[] reverse(Object[] arr) {
List<Object> list = Arrays.asList(arr);
Collections.reverse(list);
return list.toArray();
}
}
Upvotes: 60
Reputation: 9642
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.
Upvotes: 351
Reputation: 1
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;
}
Upvotes: -1
Reputation: 3856
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.
Upvotes: 89
Reputation: 2943
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));
}
}
Upvotes: 1