Home Java Java-tips Data Arrays Reverse an array

Ask Questions?

View Latest Questions

Advertisement


 
 

Reverse an array
Posted on: July 26, 2006 at 12:00 AM
This version of reverse uses two subscripts: one that starts at the left (beginning) of the array, and one that starts at the right (end) of the array.

Java Notes

Reverse an array

This version of reverse uses two subscripts: one that starts at the left (beginning) of the array, and one that starts at the right (end) of the array. You can also use a for loop that goes to the middle of the array.
//========================================================= reverse
public static void reverse(int[] b) {
   int left  = 0;          // index of leftmost element
   int right = b.length-1; // index of rightmost element
  
   while (left < right) {
      // exchange the left and right elements
      int temp = b[left]; 
      b[left]  = b[right]; 
      b[right] = temp;
     
      // move the bounds toward the center
      left++;
      right--;
   }
}//endmethod reverse
A for loop to do this would replace the above 8 statements with these. Both loops are the same speed, so the choice should be for the one which is more readable to you.
for (int left=0, int right=b.length-1; left<right; left++, right--) {
    // exchange the first and last
    int temp = b[left]; b[left]  = b[right]; b[right] = temp;
}
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-02-27
Advertisement


DMCA.com