把一个数组中奇数放到前面,偶数在后。
区别奇偶数还是&0x1好用
这是用JAVA写的,好久没用过JAVA了,写这个费了一下午,累死爸爸了,和c++在细节上还是有很多的区别的。
算法的思想就是有两个指针,一个在数组最前,一个在数组最后(pBegin和pEnd),前面的指针碰到偶数就向后移动,知道碰到奇数,后面指针类似。
附代码:
import java.util.Arrays;;
public class ReorderArray {
public static void Reorder (int pBegin,int temp[]){
if(temp.length==0)
return;
int pEnd = pBegin+temp.length-1;
while(pBegin<pEnd){
while(pBegin<pEnd&&(temp[pBegin]&0x1)!=0)
pBegin++;
while(pBegin<pEnd&&(temp[pEnd]&0x1)==0)
pEnd--;
if(pBegin<pEnd){
temp[pBegin]=temp[pBegin]+temp[pEnd];
temp[pEnd]=temp[pBegin]-temp[pEnd];
temp[pBegin]=temp[pBegin]-temp[pEnd];
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]={1,2,3,4,5,6};
System.out.print(Arrays.toString(a));
Reorder(0,a);
System.out.println("");
System.out.print(Arrays.toString(a));
}
}