Example: an array of length n, put an odd number in front of the array, even to the back of the array the space complexity is O (1)
The core idea is to define two pointers, a pointer A to be scanned from the back, and a pointer b to scan backwards.
Pointer a scans to even-numbered pauses, the pointer b scans to an odd pause, and then swaps two numbers, after which the swap continues as described above, until pointer A and pointer b coincide with the stop.
In the C language & means the bitwise AND, 0x is the hexadecimal number, k&0x1 indicates that K and 0x1 are bitwise AND, the effect is the rightmost number in the binary of K,
The formula can also be used to judge the parity of K, if K is odd, the result of the calculation is 1, otherwise 0.
The public class Jishuoushu {/** * C language & means that the bitwise and, 0x is the hexadecimal number, the k&0x1 represents the K and 0x1 bitwise AND, the effect is to take K binary in the rightmost number, * This formula can also be used to judge the parity of K, If k is odd, it evaluates to 1, otherwise 0. * @param args */public static void main (string[] args) {int list[] = {1, 2, 3, 4, 5, 7, 9,};reorderoddeven (list); System.out.println ();} public static void Reorderoddeven (int list[]) {int length = List.length; System.out.println ("original array:"); 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) {
List[begin] is odd, the result is 1, otherwise 0. The even numbers continue to run, and the odd pauses 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;}} System.out.println ("Re-ordered array:"); for (int i = 0; i < length; i++) {System.out.print (List[i] + "");}}
In-depth analysis of the array reordering (placing all odd numbers in front, with all even numbers behind them)