Title: Enter an array of integers to implement a function to adjust the attribute rage of the numbers in the array, so that all the odd digits are in the first half of the array, and all the even digits are in the second half of the array.
Idea: In fact, it is the first round with the quick sorting method, from the left and right clamp force, the left to encounter even, stop, to meet the odd, stop, exchange, and then clamp force until two hands meet.
Code implementation:
PackageCom.yyq;/*** Created by Administrator on 2015/9/13.*/ Public classReorderarray { Public Static voidReorderoddeven (int[] data) { if(Data = =NULL)return; intStart = 0; intEnd = Data.length-1; //Odd put front, even put back while(Start <end) { while(Start < End && (Data[start] & 0x1)! = 0) {Start++; } while(Start < End && (Data[end] & 0x1) = = 0) {End--; } inttemp =Data[start]; Data[start]=Data[end]; Data[end]=temp; } } //==================== test Code ==================== Public Static voidPrintArray (intnumbers[]) { if(Numbers = =NULL) return; intLen =numbers.length; for(inti = 0; i < Len; ++i) System.out.print (Numbers[i]+ "\ T"); System.out.println (); } Public Static voidTest (String testname,intnumbers[]) { if(TestName! =NULL) System.out.println (testname+ "begins:"); if(Numbers = =NULL) return; System.out.println ("Test for Solution 1:"); PrintArray (numbers); Reorderoddeven (numbers); PrintArray (numbers); System.out.println (); } Public Static voidTest1 () {intNumbers[] = {1, 2, 3, 4, 5, 6, 7}; Test ("Test1", numbers); } Public Static voidTest2 () {intNumbers[] = {2, 4, 6, 1, 3, 5, 7}; Test ("Test2", numbers); } Public Static voidTest3 () {intNumbers[] = {1, 3, 5, 7, 2, 4, 6}; Test ("Test3", numbers); } Public Static voidTest4 () {intNumbers[] = {1}; Test ("Test4", numbers); } Public Static voidTest5 () {intNumbers[] = {2}; Test ("Test5", numbers); } Public Static voidTest6 () {Test ("Test6",NULL); } Public Static voidMain (string[] args) {Test1 (); Test2 (); Test3 (); Test4 (); Test5 (); Test6 (); }}
Output Result:Test1 Begins:test for Solution 1:12 3 4 5 6 7 17 3 5 4 6 2 Test2 Begins:test for Solution 1:24 6 1 3 5 7 75 3 1 6 4 2 Test3 Begins:test for Solution 1:13 5 7 2 4 6 13 5 7 2 4 6 Test4 begins:test for Solution 1:11 Test5 begins:test for Solution 1:22 Test6 begins:
P102, interview question 14: Adjust the array order so that the odd digits are preceded by even numbers