Sword means offer interview 14-adjust the array order so that the odd digits are preceded by even numbers

Source: Internet
Author: User

Topic:

Enter an array of integers to implement a function to adjust the order of the arrays 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.


Solution One: O (n^2)

Scan the array from the beginning, take out the number for each even number, and move all the numbers that are behind that number forward. After you have moved, there is an empty space at the end of the array, and the even number is placed in the empty space.

Because the O (n) numbers need to be moved every time an even number is encountered, the total complexity is O (n^2).


Solution Two: O (n)

Similar to a quick row, two pointers, one pointing to the array head, moving backwards only, one pointing to the end of the array, moving forward only. If the first pointer points to a number that is even, and the second pointer points to an odd number, the interchange is two number.


void foo (int a[],int left,int right) {    if (left>right)       return;    int i,j;    I=left;    J=right;    while (i!=j)    {        while (a[j]%2==0&&i<j) j--;        while (a[i]%2!=0&&i<j) i++;        if (i<j)             swap (a[i],a[j]);//Swap      }}


Sword means offer interview 14-adjust the array order so that the odd digits are preceded by even numbers

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.