代码
package practice;
import util.MyUtil;
import java.util.Arrays;
/**
* @author iu
* 将数值的奇数放在偶数前
* 维护2个指针,left位于0位和 right位于数值最后位,
* left找到偶数 right找到奇数 然后交换
* left和right相遇是截止
*/
public class ReorderOddEven {
public static void reorderOddEven(int[] nums){
if(nums.length == 0 || nums == null){
return;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
while (nums[left] % 2 != 0){
left++;
}
while (nums[right] % 2 == 0){
right--;
}
if(left < right){
MyUtil.swap(nums, left, right);
}
}
}
public static void main(String[] args){
int[] array = MyUtil.createArray();
System.out.println(Arrays.toString(array));
reorderOddEven(array);
System.out.println(Arrays.toString(array));
}
}
测试结果
[18, 12, 85, 50, 40, 55, 45, 12, 66, 84]
[45, 55, 85, 50, 40, 12, 18, 12, 66, 84]
[86, 8, 32, 33, 96, 3, 30, 1, 43, 66]
[43, 1, 3, 33, 96, 32, 30, 8, 86, 66]