http://www.nowamagic.net/librarys/veda/detail/257
// 用分治法求最大最小值
public static int getMax(int[] array, int i, int j) {
int Max1 = 0;
int Max2 = 0;
if (i == j) {
return Max1 = Max2 = array[j];
} else if (i == (j - 1)) {
Max1 = array[i];
Max2 = array[j];
return Max1 > Max2 ? Max1 : Max2;
} else {
int mid = (i + j) / 2;
Max1 = getMax(array, i, mid);
Max2 = getMax(array, mid, j);
return Max1 > Max2 ? Max1 : Max2;
}
}
}
假设数组的大小为8,用直接的算法,最大值最小值总需要比较14次,而用分治算法可以一次性求出最大和最小,只需要10次比较。