查找最小和使用1.5n比较得出数组中的最大值

编程入门 行业动态 更新时间:2024-10-27 10:22:36
本文介绍了查找最小和使用1.5n比较得出数组中的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正尝试在下面的代码中找出如何计算比较次数,有没有办法在代码中执行此操作?

I'm trying to figure out in the code below how to count the number of comparisons that are made, is there a way to do this in code?

也在 for循环中,它如何迭代到 a.length-1 而不是 a.length

Also in the for loop how come it iterates up to a.length - 1 and not 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); }

推荐答案

如何计算进行比较的次数?

how to count the number of comparisons that are made?

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

You add a counter variable, then increment it every time you make a value comparison, like this:

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 }

更多推荐

查找最小和使用1.5n比较得出数组中的最大值

本文发布于:2023-11-30 01:01:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648196.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最大值   组中   最小

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!