面试题 14:调整数组顺序使奇数位于偶数前面

使用两个指针,在数组头尾相对移动;

循环结束条件:头和尾重叠活着头在尾之后

左边指针右移条件:当前数是奇数

右边指针左移条件:当前数是偶数

当且仅当左边指针是偶数,右边指针是奇数,交换两个指针的值

 

此题注意扩展,函数功能的重用。

package offer;

import java.util.Arrays;

/*面试题 14:调整数组顺序使奇数位于偶数前面
题目:输入一个整数数组,实现一个函数来调整该函数数组中数字的顺序,使得所有奇数位于数组的前半部分,所有的数组位于数组的后半部分。*/
public class Problem14 {
    public static void main(String[] args) {
        Problem14 test = new Problem14();
        int[] array = new int[]{1,6,8,7,4,3,0,90,19};
        int length = array.length;
        test.SortArray(array, length);
        for(int i = 0;i<length;i++){
            System.out.print(array[i] + " ");
        }
    }
    public void SortArray(int array[],int length){
        int end = length-1;
        int start = 0;
        if(array==null || length==0){
            return;
        }
        while(start<end){
            while(!isEvent(array[start])){
                start++;
            }
            while(isEvent(array[end])){
                end--;
            }
            while(start<end && isEvent(array[start]) && !isEvent(array[end])){
                int temp = array[end];
                array[end] = array[start];
                array[start] = temp;
                start++;
                end--;
            }
        }
    }
    //判断当前位置值奇偶,偶数返回true,奇数返回false
    public boolean isEvent(int item){
        //return item && Ox01;
        return item%2==0;
    }

}

 

posted @ 2016-08-22 13:33  sunshinelym  阅读(197)  评论(0编辑  收藏  举报