調整數組順序使奇數位於偶數前面
題目:
輸入一個整數數組,實現一個函數來調整該數組中數字的順序,使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
代碼:
package com.hlq.test;
/**
* @author helongqiang
* @date 2020/5/15 23:22
*/
/**
* 輸入一個整數數組,實現一個函數來調整該數組中數字的順序,
* 使得所有的奇數位於數組的前半部分,所有的偶數位於數組的後
* 半部分,並保證奇數和奇數,偶數和偶數之間的相對位置不變。
*/
public class Solution {
public void reOrderArray(int[] array){
int len = array.length;
if(len <= 1){
return;
}
int i = 0;
while (i <= len){
if(array[i] % 2 == 1) {
i++;
}else{
int j = i + 1;
while (array[j] % 2 == 0){
if(j == len-1){
return;
}
j++;
}
int tmp = array[j];
while(j > i){
array[j] = array[j-1];
j--;
}
array[i] = tmp;
}
}
}
}