数组的反转

class reverseArray
{
    public static void main(String[] args)
    {
        int[] arr={2,3,5,1,7,8,9};

        for (int start=0,end=arr.length-1;start<end ;start++,end-- )
        {
            int temp=arr[start];
            arr[start]=arr[end];
            arr[end]=temp;
        }
        for (int x=0;x<arr.length ;x++ )
        {
            if(x!=arr.length-1)
            System.out.print(arr[x]+",");
            else
            System.out.println(arr[arr.length-1]);
        }
    }
}

输出:

9,8,7,1,5,3,2

 

以下方法,将数组反转和打印数组两个函数进行封装,以提高其复用性。

class reverseArray
{
    public static void main(String[] args)
    {
        int[] myArr={2,3,5,1,7,8,9};

        reverse(myArr);

        printArray(myArr);

        
    }
    public static void reverse(int[] arr)                    //定义数组反转函数
    {
        for (int start=0,end=arr.length-1;start<end ;start++,end-- )    
        {
            swap(arr,start,end);
        }
    }
    public static void swap(int[] arr,int start,int end)    //数组内部反转函数
    {
        int temp=arr[start];
        arr[start]=arr[end];
        arr[end]=temp;
    }
    public static void printArray(int[] arr)        //定义数组打印函数
    {
        for (int x=0;x<arr.length ;x++ )
        {
            if(x!=arr.length-1)
            System.out.print(arr[x]+",");
            else
            System.out.println(arr[arr.length-1]);
        }
    }
}

输出:

9,8,7,1,5,3,2

 

posted @ 2017-03-12 22:16  自学开发的老司机  阅读(744)  评论(0编辑  收藏  举报