Title Description
Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all the odd part of the front half of the array, is located in the second half of all the even array, and between odd and ensure a relatively even, odd and even the same position.
Thinking
First, find the first odd, removed, and then the odd element before the first all moved back one, first find the odd talk on the 0 position.
Looking at the odd element sequentially after the first odd number, and the moving operation done. We can ensure that the original relative order.
function reOrderArray(array) { let j=0; let m=0; for(let i=0;i<array.length;i++){ if(array[i]%2==1){ let temp=array[i]; let ti=i; for (; ti> 0; T i -) { array [ti] = array [ti-1] } array[0]=temp; j=i; break; } } for(++j;j<array.length;j++){ if(array[j]%2==1){ let temp=array[j]; let tj=j; for(;tj>m;tj--){ array[tj]=array[tj-1]; } array[++m]=temp; } } return array; }
If you do not consider the relative position is:
Thinking
Setting two pointers
The first pointer to start from the first element of the array, forward to aft
The second pointer from the end of the last element in the array, advancing to the head
When traversing to even start, end traversed odd, exchange the position of two numbers
When the start> end, the complete exchange
Code
function reOrderArray(array) {
if (Array.isArray(array)) { let start = 0; let end = array.length - 1; while (start < end) { while (array[start] % 2 === 1) { start++; } while (array[end] % 2 === 0) { end--; } if (start < end) { [array[start], array[end]] = [array[end], array[start]] } } } return array; }