Adjust the array order so that the odd digits are preceded by even numbers

Source: Internet
Author: User

Title: Enter an array of integers to implement a function to adjust the order of the numbers in the array so that all the odd digits are in the first half of the array, even in the second half. The complexity of the time is as low as possible.

Analysis: We can use two pointers, the first pointer initializes the first digit of the array, it moves backwards, and the second pointer initializes to the last digit of the array, and it moves forward only. Before two pointers meet, the first pointer is always in front of the second pointer. If the number that the first pointer points to is even, and the second pointer is an odd point, we swap the two numbers. The implementation code is as follows:

Void reorderoddeven (int* pdata,unsigned int length) {    if (PData==NULL || length==0)         return;             int *pBegin=pData;    int *pEnd=pData+length-1;         while (pbegin<pend)     {         while (pbegin<pend&& (*pbegin&0x1)!=0)              pBegin++;         while (pbegin<pend&& (*pbegin&0x1) ==0)              pEnd--;                     if (pbegin<pend)         {             int temp=*pbegin;             *pBegin=*pEnd;             *pend=temp;        }    }}


This article from "Fairy Road thousands of dust Dream" blog, please be sure to keep this source http://secondscript.blog.51cto.com/9370042/1583092

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.