From the surface looks like this topic is very simple, actually does not have the imagination simple, the individual thought the more difficult point is that when the odd even number has been separated but the order is not arranged, the operation of the two-part array is somewhat complicated. Two kinds of solutions are provided and we hope that we can learn from them.
Import Java.util.arrays;public class Reorderarray {public void ReOrderArrayDemo1 (int[] array) {int p1 = 0; int p2 = array.length-1; int i; while (P1 < p2) {if (Array[p1]% 2 = = 1 && P1 < p2) {//P1 value is not even, move backward p1++; } if (Array[p2]% 2 = = 0 && P2 > p1) {//p2 value is not odd, move forward p2--; }//When the value of the position of the pointer P1 is even and the value at the position of the pointer P2 is odd, the value at both positions is switched if (ARRAY[P1]% 2 = = 0 && array[p2]% 2 = = 1) {int temp = ARRAY[P1]; ARRAY[P1] = array[p2]; ARRAY[P2] = temp; }} for (i = 0; i < array.length;i++) {if (Array[i]% 2 = = 0) {//when the array element is odd, keep the pointer moving backwards until an even stop is encountered Record the position at the time of the stop; }} reorderarray.sort (array, 0, i); Reorderarray.sort (Array, I, array.length); } public static void sort (int array[], int begin, int end) {//PairThe array preceded by an even number of odd digits is sorted for (int i = Begin;i < end;i++) {int Min = i; for (int j = i + 1;j < end;j++) {if (Array[j] < array[min]) {Min = J; }} if (Min! = i) {int temp = array[min]; Array[min] = Array[i]; Array[i] = temp; }}} public void ReOrderArrayDemo2 (int[] array) {int[] Copyofarray = arrays.copyof (Array, Array.leng TH); Re-open an array to copy the original array arrays.sort (Copyofarray);//I confess my shameless direct call to the sort method =. =|| int flag = 0; Mark an array subscript/** * Iterates over the copyofarray arrays, encounters an odd number to be fetched, and puts the flag + 1 */for (int i = 0;i < copyofarray.length;i++) {if (Copyofarray[i]% 2 = = 1) {array[flag++] = Copyofarray[i]; }}/** * Iterate again, take the even number, and put it in the array, IBID. */for (int i = 0;i < copyofarray.length;i++) { if (Copyofarray[i]% 2 = = 0) {array[flag++] = Copyofarray[i]; }}} public static void Main (String args[]) {Reorderarray r = new Reorderarray (); Int[] Array = {2, 7, 1, 2, 3, 4, 5, 7, 4}; R.reorderarraydemo1 (array); System.out.println (); for (int i = 0;i < array.length;i++) {System.out.print (Array[i] + ""); } }}
The offer--> adjusts the array order so that the odd digits are preceded by even numbers and arranged in order (2 methods)