實現奇偶數排序演算法(JAVA實現)
阿新 • • 發佈:2018-12-11
給定一個整數陣列,請調整陣列的順序,使得所有奇數位於陣列前半部分,所有偶數位於陣列後半部分,時間複雜度越小越好。
package com.sort; import java.util.Arrays; public class TestSort { /** * 測試方法 * @param args */ public static void main(String[] args) { int [] a = {1,3,2,4,5,8,6,7,9}; TestSort.sortByOddEven(a); System.out.println(Arrays.toString(a)); } /** * 奇偶數排序 * @param array */ public static void sortByOddEven(int [] array){ int front = 0; int rear = array.length - 1; while (front < rear) { if(TestSort.isOdd(array[front])){ front++; } else if(TestSort.isEven(array[rear])){ rear--; } else { int temp = array[front]; array[front] = array[rear]; array[rear] = temp; } } } /** * 判斷是否是奇數 * @param num * @return boolean */ public static boolean isOdd(int num){ return (num % 2 != 0); } /** * 判斷是否是偶數 * @param num * @return boolean */ public static boolean isEven(int num){ return (num % 2 == 0); } } //程式執行結果 [1, 3, 9, 7, 5, 8, 6, 4, 2]
如果要求排好序的奇數/偶數部分都是有序的,該如何實現?