使用3n / 2比较查找最大和最小元素?

时间:2016-01-28 03:19:56

标签: algorithm

我正在尝试设计一种算法,给定n个元素的列表,在3n / 2比较中找到最小值和最大值。关于如何做到这一点的任何提示?

2 个答案:

答案 0 :(得分:3)

作为提示,想象一下所有阵列元素都是淘汰赛中的玩家。配对所有球员,并获得"赢家" (更大的数字)前进到一个锦标赛和"输家" (较小的数字)落入失败者的支架。您现在将需要考虑n / 2个赢家,并且最大值必须是其中之一,并且要考虑n / 2个输家,并且最小值必须是其中之一。在执行此操作的过程中,您进行了n / 2次比较。你能用n个剩余的比较来找到一组的最小值和另一组的最大值吗?

答案 1 :(得分:0)

@templatetypedef的提示是对的:

public static void findMinimumAndMaximumOf(int[] numbers) {
    assert numbers.length >= 2;
    List<Integer> bigList = new ArrayList<>(numbers.length / 2);
    List<Integer> smallerList = new ArrayList<>(numbers.length / 2);
    int i = 1;
    for (; i < numbers.length; i = i + 2) {
        if (numbers[i] > numbers[i - 1]) {
            bigList.add(numbers[i]);
            smallerList.add(numbers[i - 1]);
        } else {
            bigList.add(numbers[i - 1]);
            smallerList.add(numbers[i]);
        }
    }
    if ((numbers.length & 1) == 1) {
        if (numbers[numbers.length - 1] > numbers[numbers.length - 2]) {
            bigList.add(numbers[numbers.length - 1]);
        } else {
            smallerList.add(numbers[numbers.length - 1]);
        }
    }
    Iterator<Integer> iBig = bigList.iterator();
    int biggest = iBig.next();
    while (iBig.hasNext()) {
        int current = iBig.next();
        if (current > biggest) {
            biggest = current;
        }
    }
    Iterator<Integer> iSmall = smallerList.iterator();
    int smallest = iSmall.next();
    while (iSmall.hasNext()) {
        int current = iSmall.next();
        if (current < smallest) {
            smallest = current;
        }
    }
    System.out.println(String.format("Max:%d, Min:%d" ,biggest,smallest));
}