Write java program to realize array element inversion

The topic is as follows:
    Reverse of the array: Reverse the order of the elements in the array, for example, the original array is 1, 2, 3, 4, 5, and the reversed array is 5, 4, 3, 2,
    1 1. Realization idea: swap position of the farthest element of the array.
     (1) To achieve reversal, you need to exchange the positions of the farthest elements of the array;
     (2) Define two variables to save the minimum index and maximum index of the array;
     (3) Exchange positions of elements on the two indexes;
     (4) The minimum index ++, the maximum index –, exchange positions again;
     (5) The minimum index exceeds the maximum index, and the array reverse operation ends;
    2. The schematic diagram is as follows:
    Insert picture description here
    3. Code:

public static void main(String[] args) {
    
    
int[] arr = {
    
     1, 2, 3, 4, 5 };
 /*
 循环中定义变量min=0最小索引
 max=arr.length‐1最大索引
 min++,max‐‐
 */
 for (int min = 0, max = arr.length ‐ 1; min <= max; min++, max‐‐){
    
    
  //利用第三方变量完成数组中的元素交换
  int temp = arr[min];
  arr[min] = arr[max];
  arr[max] = temp;
 }
 // 反转后,遍历数组
 for (int i = 0; i < arr.length; i++) {
    
    
   System.out.println(arr[i]);
 }
}

Guess you like

Origin blog.csdn.net/Light20000309/article/details/104643921