Java algorithm implements explanation of adjusting array order so that odd numbers precede even numbers

  • 2021-06-28 12:25:40
  • OfStack

Adjust array order so odd numbers precede even numbers

1. Title Description

Enter 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 and all even numbers are in the second half of the array, keeping the relative positions between odd and odd numbers and even numbers unchanged.

2. Topic Analysis

The title is similar to a selection sort in that odd numbers are selected and placed in front of the data, keeping the relative positions of other unselected elements unchanged.

1. Traverse through the array, if the array element is odd, the condition is n% 2!=0 2. Setting a variable to label the odd number of oddNum elements that are currently traversed is also the index that places the odd number of elements in the array 3. The loop moves the even number one bit backwards between the first and last odd numbers of the element (the odd placed element is in the position of the array oddNum) and places the element in the position of oddNum+1

3. Solution code


public class Solution {
  public void reOrderArray(int [] array) {
    int oddNum = 0;
    for (int i = 0; i < array.length; i++) {
      if (array[i] % 2 != 0) {
        int temp = array[i];
        for (int j = i; j > oddNum; j--) {
          array[j] = array[j - 1];
        }
        array[oddNum] = temp;
        oddNum++;
      }
    }
  }
}

summary


Related articles: