數組的反轉

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函數

 

如下方法,將數組反轉和打印數組兩個函數進行封裝,以提升其複用性。spa

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]);
        }
    }
}

輸出:code

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

相關文章
相關標籤/搜索