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;
}