题目:使数组中的奇数位于偶数的前面
思路:在数组的前后设置指针,然后进行比较,再调整位置,即可在O(n)的时间内完成题目的要求。
基本的实现如下:
public static int[] recorder(int[] data, int length){
if(data == null || length <= 0){
return null;
}
int startIndex = 0;
int endIndex = length -1;
while(startIndex < endIndex){
while(startIndex < endIndex && isEven(data[startIndex])){
startIndex ++;
}
while(startIndex < endIndex && !isEven(data[endIndex])){
endIndex --;
}
if(startIndex < endIndex){
int temp = data[startIndex];
data[startIndex] = data[endIndex];
data[endIndex] = temp;
}
}
return data;
}
如果题目要求我们 使数组中能被3整除的位于不能被3整除的前面 或者 使数组中质数位于非质数的前面 等等条件,
为了考虑程序复用性,C++中我们可以传入一个函数指针在运行时再决定具体实现什么业务。
- void Recorder(int *pData, unsigned int length, bool (*func)(int));
使用Java反射机制,在执行时才决定调用的方法,也可实现程序的复用性,代码如下:
package cn.gt.algori;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* 调整数组顺序,使奇数位置位于偶数前面
* @author gengtao
*
*/
public class train0812_1 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int[] data = {1,2,3,4,5,6,7,8};
System.out.print(" Use isEven: ");
System.out.println(Arrays.toString(recorder(data, data.length, "isEven")));
System.out.print("Use isAliquot: ");
System.out.println(Arrays.toString(recorder(data, data.length, "isAliquot")));
}
//判断是否是奇数
public static boolean isEven(int number){
return (number & 1) == 1;
}
//判断是否能被3整除
public static boolean isAliquot(int number){
return (number % 3) == 0;
}
/**
* 前后指针调整
* @param data
* @param length
* @param funcName 函数名称
* 也可以是被3整除的在不被3整数的前面 实现复用
* @return
*/
public static int[] recorder(int[] data, int length, String funcName) throws Exception{
if(data == null || length <= 0){
return null;
}
//通过反射得到要调用的方法名
Class<?> c = Class.forName("cn.gt.algori.train0812_1");
Object obj = c.newInstance();
Method method = c.getMethod(funcName, int.class);
int startIndex = 0;
int endIndex = length -1;
while(startIndex < endIndex){
while(startIndex < endIndex && (boolean)method.invoke(obj, data[startIndex])){
startIndex ++;
}
while(startIndex < endIndex && !(boolean)method.invoke(obj, data[endIndex])){
endIndex --;
}
if(startIndex < endIndex){
int temp = data[startIndex];
data[startIndex] = data[endIndex];
data[endIndex] = temp;
}
}
return data;
}
}
打印结果如下: