Wins the Offer-13: adjusted so that the position of the array in front of the even-odd

Title Description :

Enter an array of integers, to realize a function to adjust the order of numbers in the array, such that all the odd part of the front half of the array, all even the latter half of the array is located is located, and to ensure that odd and odd, even-even and between the same relative position. For example a given array {2,4,6,3,5}, the array {3,5,2,4,6} is adjusted

A thought:

The most straightforward idea is to create a new array, the array size is the size of the original, the use of space for time.

  / * 
     * To open the array: space for time 
     * 1 through the array, if placed in the head from the odd to the original array, and the index record 
     * 2. If an even number is placed into a new array, recording the index 
     * 3. the two arrays combined, is inserted from the last even-odd 
     * / 
    public  static  void reOrderArray ( int [] array) {
         IF (array == null || be array.length == 0 )
             return ;
         int indexOdd = 0, indexEven 0 = ;
         int [] = the even new new  int [be array.length]; // store the even array 
        for ( int NUM: array) {
             IF ((& NUM. 1) ==. 1) { //If odd 
                Array [indexOdd ++] = NUM; 
            } the else { // is even, 
                the even [indexEven ++] = NUM; 
            } 
        } 
        // merge array 
        for ( int I = 0; I <indexEven; I ++ ) { 
            Array [indexOdd + I ] = the even [I]; 
        } 
    }

Thinking two:

Sort by inserting thought, without altering the relative position of the even-odd, odd-numbered forward move

    / * 
     * Insert sequencing method 
     * / 
    public  static  void reOrderArray_2 ( int [] Array) {
         IF (Array == null || be array.length == 0 )
             return ;
         int I, J, tempNum;
         for (I =. 1; I <be array.length; I ++ ) {
             iF ((Array [I] &. 1) ==. 1) { // when odd 
                = Array [I] tempNum; // storing the number of comparison 
                J =-I. 1 ;
                 the while ( J> = 0 && (Array [J] &. 1) == 0) { // current when a number is even, odd moved forward 
                    array [j + 1] = array[j];
                    j--;
                }
                array[j+1]=tempNum;
            }
        }
    }

 

Guess you like

Origin www.cnblogs.com/zengcongcong/p/11449615.html