分治法 求最大元和最小元 Java语言

public class findMaxMin {

	public static void main(String[] args) {
		int[] Max = new int[2];//由于Java 值传递 的原因,改为数组
		int[] Min = new int[2];
		int a[] = { 0, 1, 3, 4, 5, 6, 7, 2, 4, 19, 45, 23 };// 不用0位置

		new findMaxMin().findMaMi(a, Max, Min, 1, 11);
		System.out.println("Max=" + Max[1] + "  Min=" + Min[1]);
	}

	public void findMaMi(int[] a, int[] Max, int[] Min, int l, int r) {

		if (l == r) {// 只有一个元素,大小值一样
			Max[1] = Min[1] = a[r];
		} else {
			if (l == r - 1) { // 只有两个元素

				if (a[l] > a[r]) {
					Max[1] = a[l];
					Min[1] = a[r];
				} else {
					Max[1] = a[r];
					Min[1] = a[l];
				}
			} else {// 有多个元素

				int hMax[] = { 0, 0 };
				int hMin[] = { 0, 0 };
				int m = (r + l) / 2;
				findMaMi(a, hMax, hMin, l, m);
				findMaMi(a, Max, Min, m + 1, r);
				if (hMax[1] >= Max[1]) {
					Max[1] = hMax[1];
				}
				if (Min[1] >= hMin[1]) {
					Min[1] = hMin[1];
				}

			}
		}

	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值