Sword refers to offer programming question Java Implementation-interview question 14 adjust the array order so that the odd number is located before the even number, the sword refers to offer
Question:
Enter an integer array and implement a function to adjust the order of the arrays in the array so that all odd numbers are located in the first half of the array, and even numbers are located in the second half of the array.
Solution: maintain two pointers in the array. The first pointer points to the array header during initialization, the second Pointer Points to the end of the array during initialization, and the first pointer always points to an even number,The second pointer always points to an odd number. If the first pointer is before the second pointer, the two pointers are switched to the element.
1 package Solution; 2 3/** 4 * offoffoffoffer interview question 14: Adjust the array order to be an odd number located before the even number 5 * question: enter an integer array, implement a function to adjust the order of numbers in the array so that all odd numbers are located in the first half of the even number, all the even numbers are in the second half of the array 6 * @ author GL 7*8 */9 public class No14ReorderArray {10 11 public static void main (String [] args) {12 int [] array = {1, 2, 4, 5, 6, 7, 8, 9}; 13 reorderOddEven (array); 14 for (int I = 0; I <array. length; I ++) {15 System. out. print (array [I] + ","); 16} 17 18} 19 20 public static void reorde ROddEven (int [] array) {21 if (array = null | array. length <= 0) 22 throw new RuntimeException ("invalid array"); 23 int begin = 0; 24 int end = array. length-1; 25 while (begin <end) {26 while (begin <end & (array [begin] & 1 )! = 0) 27 begin ++; 28 while (begin <end & (array [end] & 1) = 0) 29 end --; 30 if (begin <end) {31 int temp = array [end]; 32 array [end] = array [begin]; 33 array [begin] = temp; 34} 35} 36} 37 38}