题目:调整数组顺序使奇数和位于偶数前面
输入:校验输入异常(为空,长度为0)
测试:
/** * 面试题14 调整数组顺序使奇数和位于偶数前面 * * 2014-1-18 */ public class ReorderArray { public int[] reorderArray(int[] arr) { if (arr == null || arr.length <= 0) { throw new NullPointerException(); } int left = 0; int right = arr.length - 1; while (left < right) { // 向后和向前遍历都需要判断是否越界 while (left < arr.length && !moveToLeft(arr[left])) { left++; } while (right >= 0 && moveToLeft(arr[right])) { right--; } if (left < right) { swap(arr, left, right); left++; right--; } } return arr; } public boolean equal(int[] arr1, int[] arr2) { for (int i = 0; i < arr1.length; i++) { if (arr1[i] != arr2[i]) { return false; } } return true; } /** * 提高扩展性,如果需要修改排序条件,只需修改此函数 * * @param value * @return */ private boolean moveToLeft(int value) { return (value & 0x1) == 0; } private void swap(int[] arr, int indexOne, int indexTwo) { int temp = arr[indexOne]; arr[indexOne] = arr[indexTwo]; arr[indexTwo] = temp; } public static void main(String[] args) { boolean flag = true; ReorderArray reorderArray = new ReorderArray(); // 只有一个元素数组 int[] arr1 = {1}; int[] result1 = {1}; reorderArray.reorderArray(arr1); flag &= reorderArray.equal(arr1, result1); // 全奇数数组 int[] arr2 = {1, 1, 1, 1}; int[] result2 = {1, 1, 1, 1}; reorderArray.reorderArray(arr2); flag &= reorderArray.equal(arr2, result2); // 全偶数数组 int[] arr3 = {8, 8, 8}; int[] result3 = {8, 8, 8}; reorderArray.reorderArray(arr3); flag &= reorderArray.equal(arr3, result3); // 既有奇数也有偶数 int[] arr4 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int[] result4 = {1, 9, 3, 7, 5, 6, 4, 8, 2, 10}; reorderArray.reorderArray(arr4); flag &= reorderArray.equal(arr4, result4); // 输入空数组 boolean tryFlag = false; try { reorderArray.reorderArray(null); } catch (NullPointerException e) { tryFlag = true; } finally { // 跑出异常才对 flag = tryFlag; } System.out.println(flag); } }
参考资料:
《剑指offer》 面试题14