• 数组的反转


    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

  • 相关阅读:
    编译安装linux内核步骤
    怎样在github上协同开发
    在JSP里使用CKEditor和CKFinder
    tomcat结合nginx使用小结
    JAVA学习笔记——(五)
    JAVA学习笔记——(四)
    JAVA学习笔记——(三)
    JAVA学习笔记——(二)
    JAVA学习笔记——(一)
    ansible
  • 原文地址:https://www.cnblogs.com/ibelieve618/p/6539671.html
Copyright © 2020-2023  润新知