Java Notes
Reverse an array
This reverse method uses two subscripts: one that starts at the left (beginning, top) of the array, and one that starts at the right (end, bottom) of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//========================================================= reverse1 public static void reverse1(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--; } } |
A for loop managing two indexes is shown below. Both loops are the same speed, so the choice should be for the one which is more readable to you. I personally find for loops with several variables difficult to read, so usually avoid them.
1 2 3 4 5 6 7 8 9 |
//========================================================= reverse2 public static void reverse2(int[] b) { for (int left=0, right=b.length-1; left < right; left++, right--) { //... Exchange the left and right elements int temp = b[left]; b[left] = b[right]; b[right] = temp; } } |