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

Source: Internet
Author: User

    • Topic

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)

    • Ideas

Use two pointers low and high to point to the head and tail of the array, respectively. The low pointer slides backwards, the high pointer slides forward, the low pointer is used to find the even number, the high pointer is used to find the cardinality, and the two are exchanged, which is similar to the quick sort

    • Code implementation

 Public classAlgorithm {/**determine if the number num is odd*/     Public Static BooleanIsEven (intnum) {        /**bit operations are faster than%*/        if(num & 1) = = 1)            return true; return false; }         Public Static voidReorderoddeven (int[] source) {        intLow = 0; intHigh = Source.length-1;  while(Low <=High ) {            /**Find even numbers*/             while(IsEven (Source[low])) {++Low ; }            /**Find Odd*/             while(!IsEven (Source[high])) {                --High ; }            if(Low <=High ) {                /**Exchange*/                intTMP =Source[low]; Source[low]=Source[high]; Source[high]=tmp; }        }    }         Public Static voidMain (String []args) {int[] Array =New int[]{2,4,5,6,3,8,1};        Algorithm.reorderoddeven (array);  for(intNum:array)        {System.out.println (num); }    }}

  

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.