Reorder the array so that the odd number precedes the even number

Topic describes

Take an array of integers and implement a function to adjust the order of the numbers in the array so that all odd numbers are in the first half of the array and all even numbers are in the second half of the array, and the relative positions between odd and odd numbers and even and even numbers remain the same.

Adjust the array order so that the odd number precedes the even number

code

/** * Adjust the array in order to make odd in even the front * topic description * enter an integer array, to implement a function to adjust the order of the Numbers in the array, makes all the odd number is located in the first half of the array, all of the even number is located in the second part of the array, * and to ensure that the odd and odd, the relative position between the even number and even the same. * Title link: * https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&&tqId=11166&rp=1&ru=/ta/coding-interviews&qru =/ta/coding-interviews/question-ranking */
public class Jz13 {

    /** * Create an array **@param array
     */
    public void reOrderArray(int[] array) {
        // The number of odd numbers
        int oddCnt = 0;
        for (int x : array) {
            if (!isEven(x)) {
                oddCnt++;
            }
        }
        int[] copy = array.clone();
        int i = 0, j = oddCnt;
        for (int num : copy) {
            if (num % 2= =1) {
                array[i++] = num;
            } else{ array[j++] = num; }}}private boolean isEven(int x) {
        return x % 2= =0;
    }

    /** * Method 2: Using the bubble idea, float the current even number up to the current far right every time. Time complexity O(N2), space complexity O(1), time for space. * *@param array
     */
    public void reOrderArray2(int[] array) {
        int N = array.length;
        for (int i = N - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if(isEven(array[j]) && ! isEven(array[j +1])) {
                    swap(array, j, j + 1); }}}}private void swap(int[] nums, int i, int j) {
        intt = nums[i]; nums[i] = nums[j]; nums[j] = t; }}Copy the code

Even if the night swallowed everything, the sun can come back.