Here we introduce an efficient algorithm that can be completed within O(n) time complexity.
The core idea is: define two pointers, one pointer A scans from front to back, and one pointer B scans from back to front. Pointer A scans to an even number and pauses, pointer B scans to an odd number and pauses, and then exchanges the two numbers. After the exchange, continue scanning and exchanging as above until pointer A and pointer B coincide and stop.
The Java code of this algorithm is as follows:
Copy the code code as follows:
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] + " ");
}
}
}