标签:
题目:输入一个整数数组,实现一个函数来调整该数组中数字的属性怒,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
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]+"\t"); 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(); } }
标签:
原文地址:http://www.cnblogs.com/yangyquin/p/4924179.html