Two cases: the original order can be disrupted; the original order cannot be disrupted.
The following code is not tested, but it is just a build.
1 /************************************** * *********************************** 2> File Name: rearrangearray. CPP 3> author: zhoukang1991 4> mail: [email protected] 5> created time: thursday, August 28, 2014, 54 seconds, 6 ******************************* **************************************** */7 8 # include <iostream> 9 # include <vector> 10 # include <algorithm> 11 using namespace STD; 12 13 // keep the original se Quence14 // It is similar to insert sorting, but it is processed from left to right. Each time it finds a condition that is less than the group 15 //, it will find the matching result, and the array is shifted to 16 void rightrotate (vector <int> & arr, int outofplace, int cur) {17 int TMP = arr [cur]; 18 for (INT I = cur; i> outofplace; -- I) {19 arr [I] = arr [I-1]; 20} 21 arr [outofplace] = TMP; 22} 23 24 void rearrangearray_1 (vector <int> & ARR) {25 int n = arr. size (); 26 int outofplace =-1; 27 for (INT I = 0; I <n; ++ I) {28 If (outofplace> = 0) {29 If (ARR [I]> = 0) & (ARR [outofplace] <0) | (ARR [I] <0) & (ARR [outofplace]> = 0 ))) {30 rightrotate (ARR, outofplace, I); 31 if (I-outofplace> 2) {32 outofplace = outofplace + 2; 33} 34 else {35 outofplace =-1; 36} 37} 38} 39 if (outofplace =-1) {40 if (ARR [I]> = 0 )&&(! (I & 0x01) | (ARR [I] <0) & (I & 0x01) {41 outofplace = I; 42} 43} 44} 45} 46 47 // you do not need to keep the original sequence 48 // similar to a fast sorting: The two pointers traverse from the beginning to the end, if the condition is not met, the 49 int check (int v, int ID) {50 if (V> = 0 )&&(! (ID & 0x01) {51 return 1; 52} 53 else if (v <0 )&&(! (ID & 0x01) {54 return-1; 55} 56 return 0; 57} 58 void rearrange_2 (vector <int> & ARR) {59 int n = arr. size (); 60 int left, right; 61 while (left <n & right <n) {62 for (; left <n; ++ left) {63 If (check (ARR [left], left) = 1) {64 break; 65} 66} 67 for (; right <n; ++ right) {68 if (check (ARR [right], right) =-1) {69 break; 70} 71} 72 swap (ARR [left], arr [right]); 73 left ++; 74 right ++; 75} 76} 77 78 int main () {79 return 0; 80}
Rearrange the array so that the negative number is followed by a positive number and the space of O (1 ).