The sword refers to Offer-Java- Adjusting array order so that odd numbers come before even numbers

Reorder array so odd numbers come before even numbers


Question:
Input 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, all even numbers are in the second half of the array, and between odd and odd, even and even The relative position remains unchanged.
Code:

package com.hlq.test;

/**
 * @author helongqiang
 * @date 2020/5/15 23:22
 */

/**
 * 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,
 * 使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后
 * 半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
 */

public class Solution {
    
    

    public void reOrderArray(int[] array){
    
    
        int len = array.length;
        if(len <= 1){
    
    
            return;
        }
        int i = 0;
        while (i <= len){
    
    
            if(array[i] % 2 == 1) {
    
    
                i++;
            }else{
    
    
                int j = i + 1;
                while (array[j] % 2 == 0){
    
    
                    if(j == len-1){
    
    
                        return;
                    }
                    j++;
                }
                int tmp = array[j];
                while(j > i){
    
    
                    array[j] = array[j-1];
                    j--;
                }
                array[i] = tmp;
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324127788&siteId=291194637