题目:老板有一袋金块(共 n 块,n 是 2 的幂( n ≥ 2 )),最优秀的雇员得到其中最重的一块,最差的雇员得到其中最轻的一块。假设有一台比较重量的仪器,希望用最少的比较次数找出最重和最轻的金块。并对自己的程序进行复杂性分析。
import java.util.Scanner; public class Main { private static void minmax(int i, int j, int[] gold, int[] result) { int[] ltemp = new int[2]; int[] rtemp = new int[2]; if (i == j - 1) { if (gold[i] <= gold[j]) { result[0] = gold[i]; result[1] = gold[j]; } else { result[0] = gold[j]; result[1] = gold[i]; } } else { int mid = (i + j) / 2; minmax(i, mid, gold, ltemp); minmax(mid + 1, j, gold, rtemp); if (ltemp[0] <= rtemp[0]) { result[0] = ltemp[0]; } else { result[0] = rtemp[0]; } if (ltemp[1] >= rtemp[1]) { result[1] = ltemp[1]; } else { result[1] = rtemp[1]; } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int[] gold = new int[n]; for (int i = 0; i < n; i++) { gold[i] = scanner.nextInt(); } int[] result = new int[2]; minmax(0, n - 1, gold, result); System.out.println("min: " + result[0]); System.out.println("max: " + result[1]); } scanner.close(); } }
原文地址:http://blog.csdn.net/u011506951/article/details/34934621