|
发表于 2004-6-28 21:34:17
|
显示全部楼层
今天刚考完算法!
-
- /*
- * Created on 2004-6-26
- * MaxMin.java
- */
- /**
- * @author acdy
- * 算法 2.6 递归求取最大和最小元素
- */
- public class MaxMin {
- private int n;
- private double[] A;
- private double fmax;
- private double fmin;
-
- public MaxMin(double[] A) {
- this.A = A;
- n = A.length -1;
- }
- // 递归求取最大和最小元素
- public void maxMin(int i,int j) {
- // 把最大A(i,j)中的最大值和最小值分别赋给fmax和fmin
-
- if(i==j) {
- fmax = fmin = A[i];
- }
- else if(i==j-1) {
- if(A[i]<A[j]) {
- fmax = A[j];fmin = A[i];
- }
- else {
- fmax = A[i];fmin = A[j];
- }
- }
- else {
- int mid = (int)Math.floor((i+j)/2);
- double gmax,gmin,hmax,hmin;
- maxMin(i,mid);
- gmax = fmax;
- gmin = fmin;
-
- maxMin(mid+1,j);
- hmax = fmax;
- hmin = fmin;
-
- fmax = Math.max(gmax,hmax);
- fmin = Math.min(gmin,hmin);
- }
- }
-
- // 显示结果
- public void print() {
- System.out.println("最大值为:\t"+ fmax);
- System.out.println("最小值为:\t"+ fmin);
- }
- public static void main(String[] args) {
- // 下标从一开始
- double[] A={0,22,13,-5,-8,15,60,17,31,47};
- // 初始化
- MaxMin test = new MaxMin(A);
-
- // 递归求取最大和最小元素
- test.maxMin(1,A.length-1);
-
- // 显示结果
- test.print();
- }
- }
复制代码
需要比较的次数
T(n) =
0 (n=1)
1 (n=2)
T(floor(n/2))+T(ceil(n/2)) + 2 (n>2)
当n = 2 的幂时 T(n)=2T(n/2)+2 ;3n/2-2 是最好,平均及最坏情况的比较次数 |
|