题目
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
分析
对于数组的操作,插入是比较耗时的, 因为要移动插入位置之后的所有元素,腾出一个空位,供元素插入。所以对数组的操作,尽量是交换不同位置的元素。
因此我们维护两个指针front和tail,front初始化时指向数组的第一个数字,它只向后移动;tail指针初始化时指向数组的最后一个数字,它只向前移动。在两个指针相遇之前,front指针总是在tail之前。如果front指向的数字是偶数,且tail指针指向的是奇数,则交换两个数字。
代码
public static void reorderOddEven(int [] arr) {
if(arr == null || arr.length <= 0) {
return;
}
int front = 0;
int tail = arr.length - 1;
while(front < tail){
while(front < tail && (arr[front] & 1) == 0){
front++;
}
while(front < tail && (arr[tail] & 1) == 0) {
tail -- ;
}
if(front < tail) {
int temp = arr[front];
arr[front] = arr[tail];
arr[tail] = temp;
}
}
}