1. 題目描述
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
2.解題思路
(1)第一個思路:類似冒泡算法,前偶後奇數就交換,這裏要注意考慮儘可能多的情況:
public class Reorderarray {
public static void main(String [] args) {
//int [] array = {0,1,3,5,6,7,8,9};
int [] array = {2,4,6,1,3,5,7};
for (int i=0; i<array.length-1; i++) {
for (int j=0; j<array.length-1; j++) {
if(array[j]%2==0 && array[j+1]%2==1) {
int t=array[j];
array[j]=array[j+1];
array[j+1]=t;
}
//System.out.println(j+" "+Arrays.toString(array));
}
}
System.out.println(Arrays.toString(array));
}
}
運行結果:
[1, 3, 5, 7, 2, 4, 6]
(2)第二個思路:另外創建2個數組,用於把奇偶分別保存,最後再按先奇數後偶數的順序填入到Array中。
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class Reorderarray {
public static void main(String [] args) {
int [] array = {0,1,3,5,6,7,8,9};
//int [] array = {2,4,6,1,3,5,7};
List<Integer> odd = new ArrayList<Integer>();
List<Integer> even = new ArrayList<Integer>();
int temp = 0;
for (int j=0; j<array.length; j++) {
temp=array[j];
if(temp%2==1) {
odd.add(temp);
}else {
even.add(temp);
}
int m = 0;
for(int jj = 0;jj < odd.size();jj++){
array[m] = odd.get(jj);
m++;
}
for(int i=0; i < even.size(); i++){
array[m] = even.get(i);
m++;
}
}
System.out.println(odd);
System.out.println(even);
System.out.println(Arrays.toString(array));
}
}
運行結果:
[1, 3, 5, 7, 9]
[0, 6, 8]
[1, 3, 5, 7, 9, 0, 6, 8]