给定一组数组,奇数位于数组前面,偶数位位于数组后面
方法有两种
方法一
我们先对原来数组遍历一遍,给一个count,记录偶数的个数;然后我们在创建一个新的数组,再遍历一遍,把奇数放在这个新的数组前面,偶数放在新数组后面,最后新的数组赋值给原来的数组,就完成了奇偶的排序。
public class jioushuzu {
public static void main(String[] args){
int [] array={1,2,3,4,5,6,7,8};
int length=array.length;
int count=0;
for(int i=0;i<length;i++)
{
if(i%2==0)
count++;
}
int a=0;
int b=count;
int[] temp=new int[length];
for(int j=0;j<length;j++){
if(array[j]%2==0)
temp[b++]=array[j];
else
temp[a++]=array[j];
}
for(int i=0;i<length;i++){
array[i]=temp[i];
}
for(int i=0;i<length;i++)
{
System.out.println(array[i]);
}
}
}
运行结果
方法二
第二个方法,不用创建数组,在原始数组上,确定起始,终止位置,从后进行遍历,这样的速度可以加快寻找过程。
public class shuzu2 {
public static void main(String[] args){
int[] array={1,2,3,4,5,6,7,8};
int length=array.length;
for(int i=0;i<length;i++){
for(int j=length-1-i;j>0;j--){
if(array[j]%2==1&&array[j-1]%2==0){
int temp=array[j];
array[j]=array[j-1];
array[j-1]=temp;
}
}
}
for(int i=0;i<length;i++){
System.out.println(array[i]);
}
}
}
运行结果