核心思想是:定义两个指针,一个指针A从前往后扫描,一个指针B从后往前扫描。指针A扫描到偶数暂停,指针B扫描到奇数暂停,然后交换着两个数,交换之后继续如上述扫描和交换,直到指针A和指针B重合停止。
这个算法的Java代码如下:
代码如下:
package Reorder;
public class Reorder {
public static void main(String[] args) {
int[] list = { 1, 2, 3, 4, 5, 7, 9, 11 };
reorderOddEven(list);
}
public static void reorderOddEven(int[] list) {
int length = list.length;
for (int i = 0; i length; i++) {
System.out.print(list[i] + " ");
}
System.out.print("n");
int begin = 0;
int end = length - 1;
while (begin end) {
while (begin end && (list[begin] & 0x1) != 0)
begin++;
while (begin end && (list[end] & 0x1) == 0)
end--;
if (begin end) {
int temp = list[begin];
list[begin] = list[end];
list[end] = temp;
}
}
for (int i = 0; i length; i++) {
System.out.print(list[i] + " ");
}
}
}