[Array] Array element segmentation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.