Java & Programming 15 Oct 2007 08:02 pm
Reverse an Array in Place
I was just looking through some code. I noticed that an array needed to be reversed and that the original order was never needed again. This was a perfect time to reverse the array in place. This was Java so I looked in the Arrays class. But alas there wasn't a reverse for primitive arrays! Java Lists get a reverse method in the Collections class. But primitive arrays get no such love.
Also, I thought of using the asList method from Arrays, but that just seems like a ton of overhead.
So instead I wrote a quick little method for ints and any other primitive type.
Here is the int example:
-
public static void reverseInPlace(int[] iar) {
-
final int length = iar.length;
-
final int halfLength = length / 2;
-
final int lengthMinus1 = length - 1;
-
for (int i = 0; i <halfLength; ++i) {
-
final int index2 = lengthMinus1 - i;
-
-
//swap
-
int tmp = iar[i];
-
iar[i] = iar[index2];
-
iar[index2] = tmp;
-
}
-
}
Basically, this method just swaps the items from the front to back until reaching the middle of the array. If the loop continued on, it would just switch everything back and the original order would be preserved!
The other implementations for the rest of the primitive types can be found here.