Array resort of an in depth analysis of how to put all the odd Numbers in front of all the even Numbers
- 2020-04-01 02:07:26
- OfStack
Here is an efficient algorithm that can be implemented in order (n) time complexity.
The core idea is: Define two Pointers, one pointer A to scan from front to back and one pointer B to scan from back to back. Pointer A scans to an even number to pause, pointer B scans to an odd number to pause, and then exchanges the two Numbers. After the swap, continue to scan and swap as mentioned above, until pointer A and pointer B coincide to stop.
The Java code of this algorithm is as follows:
The core idea is: Define two Pointers, one pointer A to scan from front to back and one pointer B to scan from back to back. Pointer A scans to an even number to pause, pointer B scans to an odd number to pause, and then exchanges the two Numbers. After the swap, continue to scan and swap as mentioned above, until pointer A and pointer B coincide to stop.
The Java code of this algorithm is 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] + " ");
}
}
}