美文网首页
给一个数组,把偶数放到左边,奇数放到右边

给一个数组,把偶数放到左边,奇数放到右边

作者: tingshuo123 | 来源:发表于2018-08-07 10:33 被阅读14次

如题:

package hello;

public class array {

    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
        System.out.println(test(arr));

    }

    public static int[] test(int[] arr) {

        int l = 0; // 左边开始下标
        int r = arr.length - 1; // 右边开始下标

        while (l < r) {

            // 查找奇数
            while (arr[l] % 2 == 0) {
                l++;
            }
            // 查找偶数
            while (arr[r] % 2 == 1) {
                r--;
            }

            if (l < r)
                break;
            
            // 互换
            int t = arr[l];
            arr[l] = arr[r];
            arr[r] = t;

        }

        return arr;
    }
}


相关文章

网友评论

      本文标题:给一个数组,把偶数放到左边,奇数放到右边

      本文链接:https://www.haomeiwen.com/subject/akjovftx.html