使用双指针,一个从头开始,一个从尾部开始,若第一个遇到偶数,且第二个遇到奇数则互换,结束的条件就是指针相遇。
package twoPointer;
public class jishuoushi {
private static void change(int[] a) {
if (a.length == 0 || a == null) {
return;
}
int i = 0, j = a.length - 1;
while (i < j) {
while ((a[i] & 0x1) == 1 && i < j) {
i++;
}
while ((a[j] & 0x1) != 1 && i < j) {
j--;
}
if (i < j) {
int tmp = a[i];
a[i] = a[j];
a[j] = a[i];
}
}
}
public static void main(String[] args) {
int [] tes={1,4,2,1,7,3,1,9,6};
change(tes);
for(int i=0;i<tes.length;i++){
System.out.print(tes[i]+"\t");
}
}
}
本文介绍了一种使用双指针技术在数组中将所有偶数移到前面、所有奇数移到后面的方法。通过从头部和尾部同时进行扫描,并在遇到符合条件的元素时进行交换,实现了高效地对数组中的奇偶数进行重新排列。
1778

被折叠的 条评论
为什么被折叠?



