/**题目:给定一个存放整数的数组,重新排列数组使得左边为奇数右边为偶数
* 思路:
* 定义两个指针left,right遍历数组左右向中间靠拢,如果左偶数右奇数交换
* 如果左为奇数,++left;
* 如果右为偶数,--right;
* @date 2016年7月6日
*/
public class 左边为奇数右边为偶数 {
//是否为偶数
public static Boolean isEven(int n){
return (n&1)==0?true:false;
}
public static void leftOddRightEven(int []a){
int []temp=a;//临时数组
int left=0;
int right=a.length-1;
while(left<right){
if(isEven(temp[left])&&!isEven(temp[right])){//左偶右奇
temp[left]^=temp[right];
temp[right]^=temp[left];
temp[left]^=temp[right];
}
if(!isEven(temp[left])){//左奇
++left;
}
if(isEven(temp[right])){//右偶
--right;
}
}
System.out.println(Arrays.toString(temp));
}
public static void main(String[] args) {
int []a={1,2,3,4,5,6,7,8,9};
leftOddRightEven(a);
}
}
重新排列数组使得左边为奇数,右边为偶数
最新推荐文章于 2024-02-29 14:59:24 发布