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

题目:输入一个整数数组,实现一个函数来调整该数组中数字的属性怒,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。

思路:其实就是用快速排序法的第一轮排序,从左右夹逼,左边遇到偶数,停下来,右边遇到奇数,停下来,交换,再夹逼,直到两个指针相遇。
 
代码实现:
package com.yyq;

/**
 * Created by Administrator on 2015/9/13.
 */
public class ReorderArray {
    public static void reorderOddEven(int[] data){
        if(data == null) return;
        int start = 0;
        int end = data.length - 1;
        //奇数放前面,偶数放后面
        while(start < end){
            while(start < end && (data[start] & 0x1) != 0){
                start++;
            }
            while(start < end && (data[end] & 0x1) == 0){
                end--;
            }
            int temp = data[start];
            data[start] = data[end];
            data[end] = temp;
        }
    }


    // ====================测试代码====================
    public static void printArray(int numbers[])
    {
        if(numbers == null)
            return;
        int len = numbers.length;
        for(int i = 0; i < len; ++i)
            System.out.print(numbers[i]+"	");
        System.out.println();
    }

    public static void Test(String testName, int numbers[])
    {
        if(testName != null)
            System.out.println(testName+" begins:");
        if (numbers == null)
            return;
        System.out.println("Test for solution 1:");
        printArray(numbers);
        reorderOddEven(numbers);
        printArray(numbers);
        System.out.println();
    }

    public static void Test1()
    {
        int numbers[] = {1, 2, 3, 4, 5, 6, 7};
        Test("Test1", numbers);
    }

    public static void Test2()
    {
        int numbers[] = {2, 4, 6, 1, 3, 5, 7};
        Test("Test2", numbers);
    }

    public static void Test3()
    {
        int numbers[] = {1, 3, 5, 7, 2, 4, 6};
        Test("Test3", numbers);
    }

    public static void Test4()
    {
        int numbers[] = {1};
        Test("Test4", numbers);
    }

    public static void Test5()
    {
        int numbers[] = {2};
        Test("Test5", numbers);
    }

    public static void Test6()
    {
        Test("Test6", null);
    }

    public static void main(String[] args)
    {
        Test1();
        Test2();
        Test3();
        Test4();
        Test5();
        Test6();
    }
}
输出结果:
Test1 begins:
Test for solution 1:
1 2 3 4 5 6 7
1 7 3 5 4 6 2
 
Test2 begins:
Test for solution 1:
2 4 6 1 3 5 7
7 5 3 1 6 4 2
 
Test3 begins:
Test for solution 1:
1 3 5 7 2 4 6
1 3 5 7 2 4 6
 
Test4 begins:
Test for solution 1:
1
1
 
Test5 begins:
Test for solution 1:
2
2
 
Test6 begins:
 
原文地址:https://www.cnblogs.com/yangyquin/p/4924179.html