#调整数组顺序使奇数位于偶数前面
1. 不保证数组相对顺序
指定两个指针pBegin和pEnd,在pBegin<pEnd的状态下分别从前后判断是否满足pBegin指向奇,pEnd指向偶。也就是说,这两个指针分别从两端往中间遍历,pBegin碰到偶时暂停,pEnd碰到奇数暂停,如果此时仍旧在pBegin<pEnd的状态下,交换两数,使整个数组满足前面的都是奇数,后面的都为偶。直至遍历完整个数组(pBegin>=pEnd时),也就满足了整个数组都是奇在偶数前。
public class Solution21 {
public void reOrderArray(int [] array) {
int pBegin = 0 ;
int pEnd = pBegin + array.length - 1;
while (pBegin < pEnd){
while (pBegin < pEnd && funcpBegin(array[pBegin])){
pBegin++;
}
while (pBegin < pEnd && funcpEnd(array[pEnd])){
pEnd--;
}
if (pBegin<pEnd){
int temp = array[pEnd];
array[pEnd] = array[pBegin];
array[pBegin] = temp;
}
}
}
private boolean funcpBegin(int num){
if (num%2 == 0){
return false;
}
return true;
}
private boolean funcpEnd(int num){
if (num%2 != 0){
return false;
}
return true;
}
}
2.需要保证相对顺序的情况下
###2.1 暴力解
从头开始遍历数组,遇到偶就将数组后面的数字全部往前移一个,再将偶数排在最后,此种方法复杂读为o(n^2)。
###2.2 improved
- 要想保证原有次序,则只能顺次移动或相邻交换。
- i从左向右遍历,找到第一个偶数。
- j从i+1开始向后找,直到找到第一个奇数。
- 将[i,…,j-1]的元素整体后移一位,最后将找到的奇数放入i位置,然后i++。
- 終止條件:j向後遍歷查找失敗。
public void reOrderArray(int [] array) {
int pBegin = 0 ;
while (pBegin < array.length){
while (pBegin < array.length && funcpBegin(array[pBegin])){
pBegin++;
}
int pEnd = pBegin + 1;
while (pEnd < array.length && funcpEnd(array[pEnd])){
pEnd++;
}
if (pEnd<array.length){
int temp = array[pEnd];
for (int pEnd2 = pEnd-1 ; pEnd2>=pBegin ; pEnd2--){
array[pEnd2+1] = array[pEnd2];
}
array[pBegin] = temp;
}else {
break;
}
}
}