题目大致为:
对于一个数组,实现一个函数使得所有奇数位于数组的前半部分,偶数位于数组的后半部分。
思路:
使用双指针的方式,一个指针指向数组的开始,一个指针指向数组的尾部, 如果头部的数为偶数且尾部的数是奇数则交换(&&),
否则头部指针向后移动,尾部指针向前移动,直到两个指针相遇.
public class Test14 {
public void adjust(int []a){
if (a.length<=0) {
return;
}
int i=0,j=a.length-1;
int temp=0;
while(i<j){
if(a[i]%2==0 && a[j]%2==1){
temp=a[j];
a[j]=a[i];
a[i]=temp;
i++;
j--;
}else if(a[j]%2!=1){
j--;
}else if (a[i]%2!=0) {
i++;
}
}
}
public static void main(String[] args) {
int A[] = { 1, 2, 3, 4, 5,6 };
Test14 test14=new Test14();
test14.adjust(A);
System.out.println(Arrays.toString(A));
}
}