zoukankan      html  css  js  c++  java
  • 数组的反转

    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目录结构详解
    Linux快捷键列表
    正则表达式
    Python内置函数7
    Python内置函数6
    Python内置函数5
    什么才是java的基础知识?
    单点登录原理与简单实现
    window系统 查看端口 被哪个进程占用了
    Linux Tomcat日志查看实用命令
  • 原文地址:https://www.cnblogs.com/ibelieve618/p/6539671.html
Copyright © 2011-2022 走看看