How can I reverse an array in place (without creating a new array)?
-
What language? Also see http://stackoverflow.com/questions/1469311/reverse-array-in-place http://stackoverflow.com/questions/585257/is-there-a-better-way-to-reverse-an-array-of-bytes-in-memory +many others. – Dipstick Nov 08 '09 at 14:02
13 Answers
public static int[] reverseArrayWithoutTempArray(int[] array) {
int i = 0, j = array.length - 1;
for (i = 0; i < array.length / 2; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}

- 3,190
- 1
- 22
- 26
Homework means pseudo-code only from me, which you've made relatively easy by not specifying what language you want anyway :-)
Turn this into your language of choice:
Set i1 to index of first element in array
Set i2 to index of last element in array
while i1 < i2:
Set temporary variable to element number i1
Set element number i1 to element number i2
Set element number i2 to temporary value
Add 1 to i1
Subtract 1 from i2
An ideal thing to do is to actually run that algorithm in your head, using a piece of paper to keep track of variables:
- each the elements in the array.
i1
andi2
.temporary variable
.
I tend to do that for simpler algorithms. Harder ones I insert debug statement into so that the computer can do that grunt work for me. Start with a piece of paper thus:
i1 | i2 | tempvar | el[0] | el[1] | el[2] | el[3] | el[4] | el[5]
---+----+---------+-------+-------+-------+-------+-------+------
H e l l o !
and just run through the steps one by one, checking and/or changing each column as you go. That will result in you understanding how it works far better than just being given some code.

- 854,327
- 234
- 1,573
- 1,953
Reverse an array of characters without creating a new array using java.
import java.util.*;
//Reverse string array
public static void reverseArray(String[] array){
int middle = array.length / 2;
String temp;
int j = array.length -1;
for (int i = 0 ; i < middle; i++) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
System.out.println(Arrays.toString(array));
}
If you want to reverse int array, you have to change public static void reverseArray(String[] array)
as public static void reverseArray(int[] array)
and String temp
as int temp
.
Example:
public static void main (String[] args) throws java.lang.Exception{
String[] array = {"Smith", "Peter", "Michel", "John"};
reverseArray(array);
}
Output :
[John, Michel, Peter, Smith]

- 153
- 12
Swap the ends constantly, using a single variable as a temporary buffer. In pseudo-code:
temp = a[0]
a[0] = a[size - 1]
a[size - 1] = temp
and so on.

- 12,703
- 5
- 41
- 41
-
-
If you use a compiler written in the last couple of decades, it will optimize it better for the architecture it's on ( which may be XOR, or may use a register temporary ) – Pete Kirkham Nov 08 '09 at 13:10
-
If you use the xor swap method, you can eliminate the temporary. In pseudocode: a[curr] = a[curr] xor a[size - curr] a[curr] = a[curr] xor a[size - curr] a[curr] = a[curr] xor a[size - curr] ++curr – Jeff Paquette Nov 08 '09 at 13:10
-
-
@flyfishr64 - **Bad idea. Do not** use the XOR swap method here. If there is an odd number of array elements (or 1 element), XOR swapping an element with itself will result in 0. If you have to check this condition, you might as well just use the temp variable – Robert Cartaino Nov 08 '09 at 13:25
-
-
@Robert if you don't check that condition in `for (int start = 0, end = length-1; start < end; ++start,--end) swap(array,start,end);` , how will the loop terminate? – Pete Kirkham Nov 08 '09 at 16:07
-
@Pete - No, I was talking about *not* using the XOR swap method because there are special conditions you have to check for. Read this article (and responses) for details about why this is a bad idea: http://www.codeproject.com/Feature/WickedCode.aspx?msg=2565905#xx2565905xx. Even if the code works, the XOR swap has been a **terrible optimization** for a very long time anyway. – Robert Cartaino Nov 09 '09 at 16:35
public static void main(String args[]){
int j=arr.length;
for(int i=0;i<arr.length/2;i++){
int temp=arr[i];
arr[i]=arr[j-1-i];
arr[j-1-i]=temp;}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}

- 146
- 1
- 8
reversing an array of characters without creating a new array
public static void main(String[] args) {
char[] a = {'1', '2', '3','4'};
char temp = ' ';
for (int i = 0; i < a.length / 2; i++) {
temp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = temp;
}
System.out.println(a);
}

- 11
- 3
Dont bother reversing the array in memory, just iterate over it backwards!

- 4,224
- 1
- 20
- 23
-
If you were to pass the array to a library function that iterates forwards but you need it reversed, then you would have to reverse the array in memory to do so. But, in some cases, you are correct. – alternative Nov 08 '09 at 13:24
Here is the solution to reverse an array elements without using temp variable or another array. This will work only Java 8 and above version.
void invertUsingStreams(Object[] arr2) {
IntStream.rangeClosed(1,arr2.length)
.mapToObj(i -> arr2[arr2.length-i])
.forEach(System.out::println);
}
Thanks,

- 1,420
- 18
- 34
Here is a complete program, just copy paste and run it in your IDE :
public class ReverseArrayWithoutAnotherArray {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int middle = array.length / 2;
int temp;
int j = array.length -1;
for(int a : array){
System.out.println(" before reverse :: " + a);
}
for (int i = 0 ; i < middle; i++, j--) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
for(int a : array){
System.out.println(" after reverse :: " + a);
}
}
}
output :
before reverse :: 1
before reverse :: 2
before reverse :: 3
before reverse :: 4
before reverse :: 5
before reverse :: 6
before reverse :: 7
before reverse :: 8
before reverse :: 9
before reverse :: 10
after reverse :: 10
after reverse :: 9
after reverse :: 8
after reverse :: 7
after reverse :: 6
after reverse :: 5
after reverse :: 4
after reverse :: 3
after reverse :: 2
after reverse :: 1

- 561
- 4
- 12
Array.prototype.reverse = function() {
for(var i = 0, j = this.length-1; i < j; i++, j--) {
var tmp = this[i];
this[i] = this[j];
this[j] = tmp;
}
return this;
};

- 61
- 5
- Use temp variables to temporary hold the variables
- use two index pointer, one is from first index and last from array length
- iterate the array till the middle of the array elements
- Below is the function i created to do the same
- it works for both even and odd size
- Input Array 1 4 3 2
- Expected Out 2 3 4 1
static int[] reverseArray(int[] a) {
int j=a.length-1; // last index pointer
int middle = a.length/2; // end condition
for (int i=0;i<middle;i++){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
j--;
}
return a;
}

- 121
- 1
- 2
var arr = [1,2,3,4,5,6]
for(let i=arr.length-2;i>=0;i--){
arr.push(arr.splice(i,1)[0])
}
console.log(arr) // [6,5,4,3,2,1]
var arr2 = [1,2,3,4,5,6]
for(let i=0,j=arr2.length-1;i<arr2.length/2;i++){
let temp = arr2[i];
arr2[i] = arr2[j-i];
arr2[j-i] = temp
}
console.log(arr2) // [6,5,4,3,2,1]

- 7,915
- 1
- 21
- 25
import java.util.Scanner;
import java.util.Arrays;
public class reversearray {
private static Scanner scanner=new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter the count value ");
int n=scanner.nextInt();
int[] value=new int[n];
System.out.println("enter the elements of an array");
for(int i=0;i<n;i++)
{
value[i]=scanner.nextInt();
}
reverse(value);
}
public static void reverse(int[] array) {
int n = array.length - 1;
int temp = 0;
int count=0;
boolean swapped = true;
int mid = n / 2;
for (int i = 0; i < mid; i++) {
temp = array[i];
array[i] = array[n - i];
array[n - i] = temp;
count++;
}
if(count==(n-mid))
{
array[mid]=array[mid];
}
else
{
temp=array[mid];
array[mid]=array[mid+1];
array[mid+1]=temp;
}
System.out.println("the reveresed array elements are: " + Arrays.toString(array));
}
}
-
Can you explain what your code does and how it differs from the existing answers that seem to be way more compact? – nvoigt Jul 27 '20 at 14:28
-
I have improvised it by including the swapping of mid value too if you divide the array with the mid value for suppose take array length of 6 then mid value would be 2 in this situation one index value remains unchanged so it should be swapped with the mid value. If the length of one half of array is not equal to other half then one value would be left so in that case mid value should also be swapped – medha tnc Jul 29 '20 at 09:24