找到Min&使用1.5n比较的数组中的最大值

时间:2018-03-02 18:23:25

标签: java comparison

我试图在下面的代码中弄清楚如何计算所做的比较次数,有没有办法在代码中执行此操作?

同样在for loop它如何迭代到a.length - 1而不是a.length

public static void minmax1(int[] a) {

    if (a == null || a.length < 1)
        return;

    int min, max;

    // if only one element
    if (a.length == 1) {
        max = a[0];
        min = a[0];
        System.out.println("min: " + min + "\nmax: " + max);
        return;
    }

    if (a[0] > a[1]) {
        max = a[0];
        min = a[1];
    } else {
        max = a[1];
        min = a[0];
    }

    for (int i = 2; i <= a.length - 1; i++) {
        if (max < a[i]) {
            max = a[i];
        } else if (min > a[i]) {
            min = a[i];
        }
    }

    System.out.println("min: " + min + "\nmax: " + max);
}

1 个答案:

答案 0 :(得分:-1)

  

如何计算所做的比较次数?

您添加一个计数器变量,然后在每次进行值比较时递增它,如下所示:

public static void minmax1(int[] a) {

    if (a == null || a.length < 1)
        return;

    int min, max, count = 0;                       // added comparison counter

    // if only one element
    if (a.length == 1) {
        max = a[0];
        min = a[0];
        System.out.println("min: " + min + "\nmax: " + max);
        return;
    }

    count++;                                       // comparison on next line
    if (a[0] > a[1]) {
        max = a[0];
        min = a[1];
    } else {
        max = a[1];
        min = a[0];
    }

    for (int i = 2; i <= a.length - 1; i++) {
        if (max < a[i]) {
            count++;                               // 1 comparison to get here
            max = a[i];
        } else if (min > a[i]) {
            count += 2;                            // 2 comparisons to get here
            min = a[i];
        } else {
            count += 2;                            // 2 comparisons to get here
        }
    }

    System.out.println("min: " + min + "\nmax: " + max);
    System.out.println("comparisons: " + count);   // print comparison counter
}