import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class Main{ /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { //System.setIn(new FileInputStream("data.in")); StreamTokenizer in = new StreamTokenizer(new BufferedReader( new InputStreamReader(System.in))); while (in.nextToken() != StreamTokenizer.TT_EOF) { int n = (int) in.nval; int evenIndex = 0, oddIndex = 0; int[] evenArr = new int[n]; int[] oddArr = new int[n]; for (int i = 0; i < n; i++) { in.nextToken(); int m = (int) in.nval; if ((m & 1) == 0) { evenArr[evenIndex++] = m; } else { oddArr[oddIndex++] = m; } } for (int i = 0; i < oddIndex; i++) { if (i > 0) { System.out.print(" "); } System.out.print(oddArr[i]); } if (oddIndex > 0) { System.out.print(" "); } for (int i = 0; i < evenIndex; i++) { if (i > 0) { System.out.print(" "); } System.out.print(evenArr[i]); } System.out.println(); } } }
扩展:当不需要关注奇偶数原来的顺序时
package com.wangzhu.algorithm; import java.util.Arrays; import java.util.Scanner; public class ArrayOddEvenMove { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while(cin.hasNext()){ int n = cin.nextInt(); int[] arr = new int[n]; while(cin.hasNext()){ for(int i = 0;i < n;i ++){ arr[i] = cin.nextInt(); } execute1(arr); System.out.println(Arrays.toString(arr)); } } } public static void execute1(int[] arr){ //记录奇数的当前位置 int start = -1; for(int i = 0, len = arr.length;i < len;i ++){ if(!isEven(arr[i])){ //当找到一个奇数,则将当前的位置的数交换到连续奇数后面 start ++; swap(i, start, arr); } } } public static void execute(int[] arr){ int left = 0, right = arr.length - 1; while(left < right){ while(left < right && !isEven(arr[left])){ left ++; } while(left < right && isEven(arr[right])){ --right; } if(left <right){ swap(left, right, arr); } } } private static boolean isEven(int num) { return (num & 1) == 0; } private static void swap(int i, int j, int[] arr){ int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }
参考:
http://www.cnblogs.com/xing901022/p/3755795.html
http://blog.chinaunix.net/uid-26548237-id-3753247.html
http://www.cnblogs.com/kaituorensheng/p/3607118.html
时间: 2024-10-10 00:03:09