[Sword refers to offer] Adjust the order of the array so that the odd numbers are in front of the even numbers

Topic description:

Input an array of integers, 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 ensure that odd and odd, even and even numbers are between The relative position remains unchanged.
Problem solving plan:
The advantage of arrays is that queries are fast, but removing and adding nodes is complicated and must be re-copied to another array.
Adjusting the order of the array in this question must be re-copied to another array. My method is to traverse the array twice by means of the head pointer and the tail pointer. The first time uses the head pointer to put the odd numbers in order (from front to back) Put it into the reapplied array, and use the tail pointer for the second time to put the even numbers in the reapplied array in order (from back to front).
Code:
import java.util.Arrays;

public class ReOrderArray {

	public static void main(String[] args) {
		
		int[] arr = new int[]{1,2,5,7,8,2,6};
		int[] arr1 = reOrderArray(arr);
		System.out.println(Arrays.toString(arr1));
		
	}

	 public static int[] reOrderArray(int[] array) {
	     int[] temp = new int[array.length];
	     int firstP=0;//head pointer
	     int lastP=array.length-1;//tail pointer
		 for(int i=0; i<array.length; i++){//From front to back
			 if(array[i] % 2 != 0){
				 temp[firstP++]=array[i];
			 }
		 }
	     for(int j=array.length-1; j>=0; j--){//From back to front
	    	 if(array[j] % 2 == 0){
	    		 temp[lastP--]=array[j];
	    	 }
	     }
	     return temp;
	 }
}


Guess you like

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