Reverse array elements 18

Flip the array elements

Case needs

A known array arr = {19, 28, 37, 46, 50}; the program implemented by the exchange of the value of the element array, the switching array arr = {50,46, 37, 28, 19}; and array element after the console output switching.

Analysis step

Thinking: inclusive exchange.
1, using a loop, defined two counters, a counter in the first position, a counter in the last position.
2, the front of the control calculator plus forward, back behind the counter is reduced.
3, how the control loop condition, a normal condition must be exchanged: i <j. (I only need to be switched back to j)

public class ExecDemo {
    public static void main(String[] args) {
        //int a = 20, b = 10;
        // 0.准备数组
        int[] arr = {19, 28 , 46, 50};
        //           i                j
        // 1、使用一个循环,定义2个计数器,一个计数器在第一个位置,一个计数器在最后一个位置。
        // i在数组的第一个索引,j在数组的最后一个索引
        for(int i = 0 , j = arr.length - 1 ; i < j ; i++ ,  j-- ){
             // 交换 i 和 j位置处的元素。
             // 2.定义一个临时变量
            int temp = arr[i]; // 19
            arr[i] = arr[j];
            arr[j] = temp ;
        }

        // 3.输出数组内容看一下!
        for(int i = 0 ; i < arr.length ; i++ ){
            System.out.print(arr[i]+" ");
        }
    }
}

Published 34 original articles · won praise 16 · views 287

Guess you like

Origin blog.csdn.net/qq_41005604/article/details/105192032