Adjust the order of the array so that odd numbers are in front of even numbers

topic:

Enter an integer array 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 between odd and odd, even and even is guaranteed The location remains unchanged.

Ideas:

  1. If you can use auxiliary arrays, the problem becomes much simpler. You can traverse twice and add odd and even numbers to the array.
  2. If you can’t open up extra space, you can use an A pointer to record how many odd numbers are currently present while traversing the array, and another B pointer to traverse backwards, and insert the first odd number after the odd number after the odd number. , At the same time all elements between the two pointers of A and B move one bit backward

Code

public class Solution {
    
    
    public void reOrderArray(int [] array) {
    
    
        int i = 0;
        for(int j = 0;j<array.length;j++){
    
    
            if((array[j]&1)==1){
    
    
                // 暂存发现的奇数
                int temp = array[j];
                // 区间整体后移一位
                for(int k=j-1;k>=i;k--){
    
    
                    array[k+1] = array[k];
                }
                // 将奇数放到前面
                array[i++] = temp;
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/109930972