数组系列文章(五) - 数组遍历

1. 数组遍历


// 基本方式一:
for(int x = 0 ;x

2. 数组反转


    /**
     * 数组反转
     */
    public static void reverse(int[] arr){
        for (int start=0,end=arr.length-1 ; start<=end ; start++,end-- ){
            int temp = arr[start] ;
            arr[start] = arr[end] ;
            arr[end] = temp ;
        }
    }

3. 数组查找


查找指定元素第一次在数组中出现的索引

    /**
     * 数组元素查找
     *      查找指定元素第一次在数组中出现的索引
     */
    public static int getIndex(int[] arr , int  value){
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value){
                return i ;
            }
        }
        return -1 ;    // 对于数组,元素在数组中不存在就返回-1
    }

    /**
     * 方法二
     */
    public static int getIndex2(int[] arr , int  value){
        int index = -1 ;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == value){
                index = i ;
                break;
            }
        }
        return index ;
    }

你可能感兴趣的:(数组系列文章(五) - 数组遍历)