Adjust the array order so that the odd digits are in front of even numbers "Microsoft interview 100 question 54th"

Source: Internet
Author: User

Title Requirements:

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).

Reference: Sword refers to the 14th question of offer.

Topic Analysis:

Using two pointers, Pbegin and pend,pbegin traverse backwards from the beginning, pEnd forward from the end, and when Pbegin encounters an even number and pEnd encounters odd numbers, swaps two digits and then continues the traversal until pbegin>pend, then ends.

Code implementation:

#include <iostream>using namespacestd;voidReorderoddeven (Char*pin,intlen);intMainvoid){    CharPstr[] ="4372173283475738495734858394"; cout<<"the original array is (in order of Chaos):"<< pStr <<Endl;    Reorderoddeven (Pstr,strlen (PSTR)); cout<<"adjusted to (odd before and even after):"<< pStr <<Endl; return 0;}voidReorderoddeven (Char*pin,intLen) {    if(Pin==null | | len<=0)        return ; Char*pbegin =PIn; Char*pend = pin+len-1;  while(pbegin<pEnd) {        //move the pbegin backwards until the value is even         while(Pbegin<pend && (*pbegin&0x01)!=0) Pbegin++; //move Pend forward until the value is odd         while(Pbegin<pend && (*pend&0x01)==0)            --pEnd; if(pbegin<pEnd) {            Chartemp = *Pbegin; *pbegin = *pEnd; *pend =temp; }    }}

Adjust the array order so that the odd digits are in front of even numbers "Microsoft interview 100 question 54th"

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.