1 public class Reverse { 2 3 /** 4 * 逆置函数 5 * 6 * @param array 7 * 需要逆置的数组 8 * @return 逆置后的数组 9 */ 10 public int[] reverse(int[] array) { 11 int size = array.length; 12 for (int i = 0; i < size / 2; i++) { 13 /* array[size - 1 - i]:下标为i值的对称下标的值 */ 14 array[i] = array[i] + array[size - 1 - i]; 15 /* 16 * 该句效果:array[size - 1 - i] = array[i] + array[size - 1 - i] -array[size - 1 - i] 17 */ 18 /* 即:array[size - 1 - i] = array[i] 下标为i的值变为i的对称下标的值 */ 19 array[size - 1 - i] = array[i] - array[size - 1 - i]; 20 /* 同理 */ 21 array[i] = array[i] - array[size - 1 - i]; 22 } 23 return array; 24 } 25 26 public static void main(String[] args) { 27 int[] array = { 0, 1, 2, 3, 4, 5 }; 28 Reverse r = new Reverse(); 29 int[] a = r.reverse(array); 30 31 /* 输出数组每一个值 */ 32 // System.out.print("逆置后的数组为:"); 33 // for (int i = 0; i < a.length; i++) { 34 // System.out.print(" " + a[i]); 35 // } 36 System.out.println("逆置后的数组为:" + Arrays.toString(a)); 37 } 38 39 }
输出结果:
逆置后的数组为:[5, 4, 3, 2, 1, 0]
分析:见代码注释
时间: 2024-08-28 16:16:15