数组元素顺序颠倒

public class SwapDemo {
    public static void main(String[] args) {
        //给数字赋值5个随机的书
        int[] arr = new int[]{
                (int) (Math.random()*1000),
                (int) (Math.random()*1000),
                (int) (Math.random()*1000),
                (int) (Math.random()*1000),
                (int) (Math.random()*1000),
        };
        System.out.println("原始数组:");
        print(arr);
        swap(arr);
        System.out.println();
        System.out.println("倒序后:");
        print(arr);
    }
//交换
    public static void swap(int[] arr) {
        int arrlen = arr.length;
        int temp;
        for(int i = 0;i < arrlen/2;i++){
            temp = arr[i];
            arr[i] = arr[arrlen-i-1];
            arr [arrlen-i-1] = temp;
        }
    }
//遍历数组
    public static void print(int[] arr) {
        for(int i =0;i < arr.length; i++){
            System.out.print(arr[i]+"  ");
        }
    }
    
}

 

posted on 2017-02-23 18:57  hgfs瑞  阅读(593)  评论(0编辑  收藏  举报

导航