Title: Enter an array of integers to implement a function to adjust the order of the numbers in the array, so that all the odd digits are in the first half of the array, all the even digits are located in the second half of the array, and the relative positions of the odd and odd, even and even are guaranteed.
Error code:
Public classSolution { Public voidReorderarray (int[] Array) { intlen=Array.Length; for(inti=0;i<len;i++){ if((array[i]&1) ==0){ intJ; for(j=i;j<len-1;j++) Array[j]=array[j+1]; inttemp; Temp=Array[i]; ARRAY[J]=temp; I--; } } }}
This code, i--this statement, leads to a dead loop. Because, to a certain stage of the array, I and its subsequent all are even, will be cyclic, and damage stability.
Correct:
Public classSolution { Public voidReorderarray (int[] Array) { intlen=Array.Length; intK=0; for(inti=0;i<len-k;i++){ inttemp; Temp=Array[i]; if((array[i]&1) ==0){ intJ; for(j=i;j<len-1;j++) Array[j]=array[j+1]; ARRAY[J]=temp; I--; K++; } } }}
This code adds a k to limit the number of cycles I have. The key is that I do not need to traverse to the last. In addition, if you want to make the odd forward, you can follow the above code and iterate from behind.
Again, completely modeled as direct insert sort, odd forward, and at the same time traversing from 0, note: After the odd number is found, it should be moved backwards from the first even, then the odd number is inserted into the first even position.
Public classSolution { Public voidReorderarray (int[] Array) { intlen=Array.Length; for(inti=0;i<len;i++){ if((array[i]&1) ==1){ intK=0; while((array[k]&1) ==1&&k<i) k++;//find the first even number in front of if(k<i) { inttemp=Array[i]; intJ; for(j=i;j>k;j--) Array[j]=array[j-1]; ARRAY[J]=temp; } } } }}
The time complexity above is O (N2), if you borrow an array, put the even number in, and then copy into the original array, you can achieve the time complexity of O (n) algorithm
Array, the odd number is placed before the even