[Sword to offer] adjust the array order so that the odd digits are preceded by even numbers

Source: Internet
Author: User

Title Description

Enter an array of integers to implement a function that adjusts the order of the numbers in the array so that all the odd digits are placed in the first half of the array, all the even digits are located in the second half of the array, and the relative positions between the odd and odd, even and even, are guaranteed.

Enter a description

Array of integers

Output description

Odd number in the former even after, adjusted array

Problem analysis

Solution one run time: 26ms occupied memory: 526k

Import Java.util.arraylist;import java.util.List; Public  class solution {     Publicvoid Reorderarray (int []Array) {if(Array. length==0||Array==NULL){return; }List<Integer> oddlist =NewArraylist<integer> ();List<Integer> evenlist =NewArraylist<integer> (); for(int i=0;i<Array. length;i++) {if(Array[i]%2==0) {Evenlist.add (Array[i]); }Else{Oddlist.add (Array[i]); }} oddlist.addall (Evenlist); for(int i=0;i<Array. length;i++) {Array[I] = Oddlist.get (i); }    }}

This idea is relatively simple, traversing an array to place the odd and even numbers in two new arrays, and then merge and then assign to the array on the line.

Solution two run time: 27ms occupied memory: 503k

 Public classSolution { Public voidReorderarray (int[]Array) {if(Array. length==0||Array==null) {return; } for(intI=0;i<Array. length-1; i++) { for(intj=0;j<Array. length-i-1; j + +) {if(Array[j]%2==0&&Array[j+1]%2==1){inttemp =Array[j];Array[j] =Array[j+1];Array[j+1] = temp; }            }        }    }}

Similar to bubble sort, think of using the array[j+1] array do not cross the border.

[Sword to offer] 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.