Java对一维数组倒叙排列

直接数组元素对换

public class ReversTest {
    public static void main(String[] args) {
        int[] arr = { 25, 4, 15, 7, 8 };
        String[] strings = { "ramer", "jelly", "bean", "cake" };
        System.out.println("===原数组=======" + Arrays.toString(arr));
        ReversTest.reverse(arr);
        ReversTest.reverseStr(strings);
        System.out.println("===倒叙数组=======" + Arrays.toString(arr));
        System.out.println("===倒叙数组=======" + Arrays.toString(strings));

    }

    /**
     * 整型数组倒叙---直接数组元素对换
     * 
     * @param arr
     * @return
     */
    public static int[] reverse(int[] arr) {
        for (int i = 0; i < arr.length / 2; i++) {
            int temp = arr[i];
            arr[i] = arr[arr.length - 1 - i];
            arr[arr.length - 1 - i] = temp;
        }
        return arr;
    }

    /**
     * 字符串数组倒叙
     * 
     * @param strArr
     * @return
     */
    public static String[] reverseStr(String[] strArr) {
        for (int i = 0; i < strArr.length / 2; i++) {
            String temp = strArr[i];
            strArr[i] = strArr[strArr.length - 1 - i];
            strArr[strArr.length - 1 - i] = temp;
        }
        return strArr;
    }

    /**
     * 整型数组倒叙---直接数组元素对换
     * 
     * @param arr
     * @return
     */
    public static int[] reverse2(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;
        }
        return arr;
    }

}

你可能感兴趣的:(java)