The method is to use two pointers. The first pointer points to the beginning and increments backward. The second Pointer Points to the end and increments forward.
# Include <stdio. h> # include <stdlib. h> void alter (int data [], int length) {int * head = data, * tail = data + length-1, temp; while (head <tail) {while (head <tail & * head % 2) head ++; // you must also judge head <tail, because the head increment may exceed the value of tail while (head <tail &&! (* Tail % 2) tail --; if (head <tail) {temp = * head; * head = * tail; * tail = temp ;}} void main () {int I, data [10] = {1, 2, 3, 4, 5, 8, 7, 6, 5, 1}; alter (data, 10); for (I = 0; I <10; I ++) printf ("% d \ t", data [I]); getch ();}
The sword means that there is also a good way of writing extensibility on the offer, which is to pass a function pointer to the alter function to determine whether to move.
This decoupling method improves code reusability.