1 //用空间换时间 新开辟一个数组(大小与原来的一样),遍历数组偶数放入新的数组中,最后将其直接放入原来数组的最后。 2 public class N13_reOrderArray { 3 public void reOrderArray(int [] array) { 4 int len=array.length; 5 int counteven=0; 6 int arrj[]=new int[len]; 7 for(int i=0;i<len;i++) { 8 if(array[i]%2==0) { 9 arrj[counteven]=deletei(array,i); 10 array[len-1-counteven]=1;//此处需要注意数组不能越界。 11 //因题目要求后续是偶数 所以为了保持后续稳定每移一次将最后置为1 12 counteven++; 13 i--; 14 } 15 } 16 int j=0; 17 for(int i=len-counteven;i<len;i++) { //从此处将偶数添加到奇数的后面 18 array[i]=arrj[j]; 19 j++; 20 } 21 /* 22 * 23 24 for(int i=0;i<len;i++) { 25 System.out.println(array[i]); 26 } 27 */ 28 } 29 private int deletei(int array[],int i) { //删除数组特定位置i的数原来最后的数不变 30 //i为下标; 31 int len=array.length; 32 int c; 33 c=array[i]; 34 if(i<len-1) { 35 for(int j=i;j<len-1;j++) { 36 array[j]=array[j+1]; 37 }} 38 39 return c; 40 } 41 public static void main(String[] args) { 42 // TODO Auto-generated method stub 43 N13_reOrderArray n13=new N13_reOrderArray(); 44 int[] a= {1,2,3,4,5,6,7}; 45 int[] b= {1,3,5,7,2,4,6}; 46 int[] c= {2,4,6,1,3,5,7}; 47 n13.reOrderArray(a); 48 n13.reOrderArray(b); 49 n13.reOrderArray(c); 50 51 } 52 53 }
原文:https://www.cnblogs.com/kexiblog/p/11064305.html