Adjust array order so that odd numbers precede even numbers
Input an integer array and implement a function to adjust the order of numbers in the array so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and ensure that the relative positions between odd and odd numbers, even and even numbers remain unchanged.
Here are two methods, each with its own emphasis.
The first method is similar to fast sorting. The two cursors move forward and backward to the middle. The front cursor stops at the even position, and the back cursor stops at the odd position. Then the two positions are exchanged. There is a problem with this method, which makes the adjusted array not in the previous order (based on the instability of quick sorting) such as [1 23 4 5 6 7], and the stable algorithm output [1 35 6 2 4 6] instability [1 7 3 5 4 6 2]
The emphasis of this method is to understand scalability, that is, to extract the judgement function separately, so that when modifying the sorting logic, such as negative number before, non-negative number after, can be divided by 3 before, can not be divided by 3 after, can only modify the logical function.
The second method is similar to insertion sort. It sets a num to store the odd numbers that have been sorted. It traverses backwards and forwards. When it encounters an even number, it bubbles one by one from the even number to the num position. This algorithm is stable in sorting, and the output array is still ordered.
public class Solution { public void reOrderArray(int [] array) { if(array == null || array.length == 0){ return; } int beginCur = 0; int endCur = array.length - 1; int swap; while(beginCur < endCur){ while(beginCur < endCur && allSolution(array, beginCur)){ beginCur++; } while(beginCur < endCur && !allSolution(array, endCur)){ endCur--; } if(beginCur < endCur){ swap = array[beginCur]; array[beginCur] = array[endCur]; array[endCur] = swap; } } } public boolean allSolution(int[] array, int cur){ return (array[cur] & 1) == 1; } }
public class Solution { public void reOrderArray(int [] array) { if(array == null || array.length == 0){ return; } int length = array.length; int numOf = 0; int j; int swap; for(int i = 0;i < length;i++){ if((array[i] & 1) == 1){ j = i; while(j > numOf){ swap = array[j]; array[j] = array[j-1]; array[j-1] = swap; j--; } numOf++; } } } }