Array element segmentation, that is, the entire array into two parts, the first half of what nature, the latter part of what nature.
Title Description:
Enter an array of integers, adjusting the order of the numbers in the array so that all the odd digits are in the first half of the array, and all the even digits are in the second half of the array. Requires a time complexity of O (n).
Here the block of the array, it is easy to associate to the fast sort of the division of the array, from the beginning to find an element with a property of 2, from the end to find an element with a property of 1, and then exchange them. So the whole thing goes on, the final result is that the first half of the elements have properties of 1, the latter part of the elements have properties of 2.
Direct code:
void Reorder (vector<int> &data) {if (data.size () = = 0) Return;int first = 0;int last = data.size ()-1;while (first < last) {while (First < last &&!iseven (Data[first])) {first++;} while (first < last && IsEven (Data[last])) {last++;} if (first < last) {swap (Data[first], data[last]);}}} BOOL IsEven (int num) {return (num & 1) = = 0;}
Here's a way to judge odd and even numbers with a bitwise and faster. At the same time, a pointer function can be passed in reorder to indicate the method of classification.
If there is another requirement now, it is required that the order of the two parts of the split between odd and odd, even and even, remain the same.
At this point you can separate an additional space to store even numbers, using space to change time. If you do not want to, you can also use the insertion sort method to complete the algorithm, but the time complexity will be O (N2).
void Reorderarray (vector<int> &array) { int odd = 0;int i = 0;int num = array.size (), while (I < num) {if (AR Ray[i]% 2 = 0) {int val = array[i];int k = 0;for (k = i; k > odd; k--) {array[k] = array[k-1];} Array[k] = val;odd++;} ++i;} While
[Array] Array element segmentation