Title Description
Enter an array of integers to implement a function that adjusts the order of the numbers in the array so that all the odd digits in the array are in the first half of the array, and all the even digits are in the second half of the array.
1, odd and odd, relative position change between even and even.
Public classTest { Public Static voidMain (string[] args) {int[] Array = {2, 4, 5, 8, 1, 3, 7, 0}; Test.reorderarray (array); for(inti=0; i<array.length; i++) {System.out.print (array[i]); } } /*** Maintain two pointers, the first pointer is initialized to point to the first number of the array, * it only moves backwards: The second pointer is initialized to the last digit of the array, and it moves forward only. * Before two pointers meet, the first pointer is always in front of the second pointer. * If the number that the first pointer points to is even, and the second pointer points to an odd number, we exchange these two numbers. * @paramArray*/ Public Static voidReorderarray (int[] Array) { //array is empty or array length is less than 2 if(Array = =NULL|| Array.Length < 2) return; intStart = 0; intEnd = Array.length-1; while(Start <end) { //find even numbers from left to right while((Array[start] & 1)! = 0) {Start++; } //find odd numbers from right to left while((Array[end] & 1)! = 1) {End--; } if(Start <end) { inttemp =Array[start]; Array[start]=Array[end]; Array[end]=temp; } } } }
2, odd and odd, the relative position between even and even is the same.
Importjava.util.ArrayList; Public classTest { Public Static voidMain (string[] args) {int[] Array = {2, 4, 5, 8, 1, 3, 7, 0}; Test.reorderarray (array); for(inti=0; i<array.length; i++) {System.out.print (array[i]); } } /*** guaranteed odd and odd, even and even relative positions unchanged *@paramArray*/ Public Static voidReorderarray (int[] Array) { //array is empty or array length is less than 2 if(Array = =NULL|| Array.Length < 2) return; ArrayList<Integer> evenlist =NewArraylist<integer> ();//store OddArraylist<integer> oddlist =NewArraylist<integer> ();//Storing even numbers for(inti=0; i< Array.Length; i++) { if((Array[i] & 1) = = 0) {Evenlist.add (array[i]); } Else{oddlist.add (array[i]); } } for(inti=0; i<array.length; i++) { if(I <oddlist.size ()) {Array[i]=Oddlist.get (i); } Else{Array[i]= Evenlist.get (I-oddlist.size ()); } } } }
The offer-adjusts the array order so that the odd digits and the even front