小言_互联网的博客

调整数组顺序使奇数位于偶数前面(Java实现)

326人阅读  评论(0)

一般实现


import java.util.Arrays;

public class E21MakeOddBeforeEven {
    //调整数组顺序使奇数位于偶数前面

    public static void reorderOddEven(int[] numbers){
        //Java中可以创建长度为0的数组,但此处也可不验证
        if (numbers == null)
            return;

        int start = 0;
        int end = numbers.length - 1;
        while(start < end){
            //start找到偶数停止前进
            while(start < end && (numbers[start] & 0x1) != 0)
                start ++;
            //end找到奇数停止前进
            while(start < end && (numbers[end] & 0x1) != 1)
                end --;

            if (start < end){
                int swap = numbers[start];
                numbers[start] = numbers[end];
                numbers[end] = swap;
            }
        }
    }

    //测试用例
    public static void main(String[] args){
        int[] a = {5, 4, 3, 2, 1};
        E21MakeOddBeforeEven.reorderOddEven(a);
        System.out.println(Arrays.toString(a));
    }
}

可扩展的实现


import java.util.Arrays;

public class E21ReorderExtensible {
    interface Event<T>{
        boolean isEvent(T t);
    }

    public static void reorderOddEven(int[] numbers, Event<Integer> event){
        //Java中可以创建长度为0的数组,但此处也可不验证
        if (numbers == null)
            return;

        int start = 0;
        int end = numbers.length - 1;
        while(start < end){
            //start找到偶数停止前进
            while(start < end && event.isEvent(numbers[start]))
                start ++;
            //end找到奇数停止前进
            while(start < end && !event.isEvent(numbers[end]))
                end --;

            if (start < end){
                int swap = numbers[start];
                numbers[start] = numbers[end];
                numbers[end] = swap;
            }
        }
    }

    public static void main(String[] args){
        Event<Integer> event = new Event<Integer>() {
            @Override
            public boolean isEvent(Integer integer) {
                return (integer & 0x1) == 1;
            }
        };
        int[] a = {5, 4, 3, 2, 1};
        E21ReorderExtensible.reorderOddEven(a, event);
        System.out.println(Arrays.toString(a));
    }

}

转载:https://blog.csdn.net/csdn_zjp/article/details/101033094
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场