I. Title Description
Input an integer array, and implement a function to adjust the order of the numbers in the array, so that all the odd numbers are in the first half of the array, all the even numbers are in the second half of the array, and ensure the relative positions between the odd numbers and odd numbers, even numbers and even numbers are unchanged.
II. Topic analysis
Note that this question requires to keep the original order position after adjusting the order of curious couple.
Therefore, the idea of solving this problem can be compared with bubble sorting, and the position of the last element will be determined after each bubble.
Three: Code
public class Solution { public void reOrderArray(int [] array) { int temp=0; for(int i=0;i<array.length-1;i++){ for(int j=0;j<array.length-1-i;j++){ if(array[j]%2==0&&array[j+1]%2==1){//If the j bit is even and the j+1 bit is odd, then it can be exchanged. temp=array[j]; array[j]=array[j+1]; array[j+1]=temp; } } } } }
test result
IV. do not care about the order after change
At first, the code I wrote was just to put the odd number before the even number. I didn't care about the order after the change. My idea is to set two variables, from the first and the last bit of the array to traverse respectively, until the two variables meet and the adjustment is completed.
Five, code
public class Oddpreven { public static int[] oddpreven(int[] array) { int i = 0; int j = array.length-1; int temp = 0; while (i < j) {//When even variables meet, it means that both the front and back parts are found. if (array[i] % 2 == 0) {//The preceding variable points to an even number if (array[j] % 2 == 1) {//Determine whether the trailing edge points to an odd number temp = array[i];//If so, swap locations array[i] = array[j]; array[j] = temp; i++;//Two variables are taking a step at the same time j--; } else { j--;//If the back side is not an odd number now, then go ahead and look for it. If the front side is even, it will not move. } } else { i++;//No even number is found in the front. There is no exchange at present. Go on. } } return array; } public static void main(String []args) { int[] array = {1, 2, 2,3,3,4,5,1,2,1}; oddpreven(array); for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } } }
Six. test result