题目:
输入一个整数数组,实现一个函数调整该数组中数字的顺序使得所有奇数位于数组前半部分,所有偶数位于数组后半部分。
分析一:
设两个指针,进行奇偶数交换。
代码一:
package offer.xzs.twentyone;
public class Demo01 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
int[] sort = sort(arr);
for (int i = 0; i < sort.length; i++) {
System.out.println(sort[i]);
}
}
public static int[] sort(int[] array) {
int left = 0;
int right = array.length - 1;
int temp;
while (left < right) {
while (left < right && array[right] % 2 == 0) {
right--;
}
while (left < right && array[left] % 2 != 0) {
left++;
}
if (left < right) {
temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
return array;
}
}
分析二:
使用额外的数组。
代码二:
package offer.xzs.twentyone;
public class Demo02 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
int[] sort = sort(arr);
for (int i = 0; i < sort.length; i++) {
System.out.println(sort[i]);
}
}
public static int[] sort(int[] array) {
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1) {
count++;
}
}
int[] copy = array.clone();
int index1 = 0;
int index2 = count;
for (int i = 0; i < copy.length; i++) {
if (array[i] % 2 != 0) {
copy[index1++] = array[i];
} else {
copy[index2++] = array[i];
}
}
return copy;
}
}