Friday, April 11, 2008

Reverse Array

Write a function which reverses the contents of an array in place.


Just swap the first one with the last one, then the second one with the next to last one, and so on. If there are an even number of elements then we swap the last two, if odd then we end up swapping the last (middle) element with itself, which is OK.


public class Reverse {

public static void swap(int[] a, int x, int y){
int t = a[x];
a[x] = a[y];
a[y] = t;
}

/** Reverses the order of the elements in a, regardless of the size of a. */
public static void reverseArray(int[] a){
//the -1 is tricky
for (int i=0; i<(a.length-1)/2; i++){
Reverse.swap(a,i,a.length - 1 -i);
}
}

//Unit testing
public static void main (String [] argv){
int[] a = new int[9];
//Should test with odd and even.
for (int i=0; i < a.length; i++){
a[i] = i*i;}
for (int i=0; i < a.length; i++){
System.out.print(a[i] + " ");}
System.out.println("");
Reverse.reverseArray(a);
for (int i=0; i < a.length; i++){
System.out.print(a[i] + " ");}
System.out.println(""); }
}



1 comment:

Ram said...

i<(a.length-1)/2 can be i<=a.length\2

ShareThis