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 achieve a cold and cold adjustment of the order of the numbers in the book group 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.

Idea: This topic requires technology to be placed in the first half of the array, even in the second half of the array, so all the odd numbers should be in front of even numbers. In other words, when we scan this array, if we find that even numbers are in front of the odd number, we can exchange their order, and then we will meet the requirements after the exchange.

So we can maintain two pointers, the first pointer to the first number of the array when initialized, he moves backwards, the second pointer initializes to the last digit of the array, and he moves forward only. Before the 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 points to an odd number, we swap the two numbers.

 Public classorder{ Public voidGetOrder (int[] Array) {        intBegin = 0; intEnd = Array.length-1; if(array==NULL|| array.length==0)return;  while(begin<end) {             while(Begin<end & (array[begin]&1)!=0) {begin++; }             while(Begin<=end & (array[end]&1) ==0) {End--; }            if(begin<end) {                inttemp =Array[end]; Array[end]=Array[begin]; Array[begin]=temp; }        }    }     Public Static voidMain (string[] args) {int[] Array = {4,2,6,1,3,5}; Order o=NewOrder ();        O.getorder (array);  for(inti=0;i<array.length;i++) {System.out.println (array[i]); }    }}

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.