"Title description"
Enter an array of integers that implements a function to invoke the order 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.
"Solutions"
1. Only the basic function of the solution, only for the novice programmer
Method: Set the head and tail two pointers, meet the conditions on the exchange until the meeting.
My code implementation is for reference only:
1 Public Static voidAdjustarray (int[] arr)2 {3 if(arr = =NULL|| Arr. Length <1)4 {5 return;6 }7 8 intStart =0;9 intEnd = arr. Length-1;Ten One while(Start <end) A { - while(Start < end) && (Arr[start]%2==1)) - { thestart++; - } - - while(Start < end) && (Arr[end]%2==0)) + { -end--; + } A at if(Start <end) - { - Swap (arr, end, start); - } - } - } in - Public Static voidSwap (int[] arr,intIndexa,intIndexb) to { + inttemp =Arr[indexa]; -Arr[indexa] =Arr[indexb]; theARR[INDEXB] =temp; *}
2. Consider the solution of extensibility, can kill offer in seconds
In the above problem, only the odd number is required to separate, if the positive numbers are separated? Can you divide it by 3?
Therefore, I can take the criteria of the classification of the judgment out, a separate form of the function of the condition, even if the need to change later, but also only to find the corresponding function modification.
My code implementation is for reference only:
1 Public Static voidAdjustarray (int[] arr)2 {3 if(arr = =NULL|| Arr. Length <1)4 {5 return;6 }7 8 intStart =0;9 intEnd = arr. Length-1;Ten One while(Start <end) A { - while(Start < end) &&!IsValid (Arr[start])) - { thestart++; - } - - while(Start < end) &&IsValid (Arr[end])) + { -end--; + } A at if(Start <end) - { - Swap (arr, end, start); - } - } - } in - Public Static BOOLIsValid (intnum) to { + returnNum%2==0; - } the * Public Static voidSwap (int[] arr,intIndexa,intIndexb) $ {Panax Notoginseng inttemp =Arr[indexa]; -Arr[indexa] =Arr[indexb]; theARR[INDEXB] =temp; +}
"Face question 14" adjusts the array order so that the odd digits are preceded by even numbers