题目
奇数下标都是奇数或者偶数下标都是偶数
java代码
package com.lizhouwei.chapter8;
/**
* @Description: 奇数下标都是奇数或者偶数下标都是偶数
* @Author: lizhouwei
* @CreateDate: 2018/5/8 21:12
* @Modify by:
* @ModifyDate:
*/
public class Chapter8_15 {
public void modify(int[] arr) {
int even = 0;
int odd = 1;
int end = arr.length - 1;
while (even < end && odd<end) {
if ((arr[end] & 1) == 0) {
swap(arr, end, even);
even = even+2;
} else {
swap(arr, end, odd);
odd = odd+2;
}
}
}
public void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
//测试
public static void main(String[] args) {
Chapter8_15 chapter = new Chapter8_15();
int[] arr = {1, 8, 3, 2, 4, 6};
System.out.println("自然数数组 arr = {1, 8, 3, 2, 4, 6}奇数下标都是奇数或者偶数下标都是偶数:");
chapter.modify(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
结果