在 Java 中使用数组更好的最小值和最大值算法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12987892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Better minimum and maximum algorithm using an array in Java
提问by user1016950
I was trying to write a simple max and min method, as I wrote it I just cant help feeling it shouldn't be this complicated….maybe Im wrong? My maximum code works like this, excuse my poor pseudo code:
我试图编写一个简单的最大值和最小值方法,正如我写的那样,我不禁觉得它不应该这么复杂......也许我错了?我的最大代码是这样工作的,请原谅我糟糕的伪代码:
Fill an array with 10 random numbers. Create a max variable initialised to 0, because 0 is the lowest max. Compare each element against the max If the element is greater then max, replace the value of max with the element in question
用 10 个随机数填充一个数组。创建一个初始化为 0 的 max 变量,因为 0 是最低的最大值。将每个元素与 max 进行比较 如果元素大于 max,则将 max 的值替换为相关元素
I don't like the fact I have to initialise max to 0, I feel there might be a better way then this?
我不喜欢我必须将 max 初始化为 0 的事实,我觉得可能有更好的方法吗?
My min code works similar except I: Compare my min is lower then the array element. If the element is lower replace min.
我的 min 代码的工作原理类似,除了我:比较我的 min 低于数组元素。如果元素较低,请更换 min。
What I really don't like about this is I have to initialise my min to the maximum random number, in this case 50.
我真正不喜欢的是我必须将最小值初始化为最大随机数,在这种情况下为 50。
My questions are: Is there a better way to do this? Is there a more efficient way to write this code?
我的问题是:有没有更好的方法来做到这一点?有没有更有效的方法来编写这段代码?
import java.util.Random;
public class Main {
public static void main(String[] args) {
//Declare min and max
int max=0;
int min;
//Array of 10 spaces
int[] ar=new int[10];
//fill an array with random numbers between 0 and 50
for(int i=0;i<10;i++)
{
ar[i]=new Random().nextInt(50);
}
//Test max algorithm
//loop trough elements in array
for(int i=0;i<10;i++)
{
//max is set to 0, there should always be a maximum of 0
//If there isnt 0 will be the maximum
//If element is greater then max
//replace max with that element
if(ar[i]>max)
{
max=ar[i];
}
}
System.out.println("The max is "+ max);
//Test min
//Initialising min to maximum Random number possible?
min=50;
for(int i=0;i<10;i++)
{
if(ar[i]<min){
min=ar[i];
}
}
System.out.println("The min is "+min);
}
}
}
回答by Alexander
You can always grab the first element of the array (i.e. numbers[0]
) as the initial value and start the loop from the second element.
您始终可以获取数组的第一个元素(即numbers[0]
)作为初始值并从第二个元素开始循环。
int[] numbers = new int[10];
int max, min;
...
min = max = numbers[0];
for(int i = 1; i < numbers.length; ++i) {
min = Math.min(min, numbers[i]);
max = Math.max(max, numbers[i]);
}
回答by Axel
Ok, while others were already posting answers, I have taken the time to edit your code into something I think would be more usable.
好的,虽然其他人已经发布了答案,但我已经花时间将您的代码编辑为我认为更有用的内容。
- Make static methods. Those can be reused.
- Use an ellipsis (...) because you then can either call the methods on array arguments like in your code, but also with a variable number of arguments as
min(5,3,8,4,1)
. - Initialize with the smallest/biggest possible number the data type provides
- To check that your code works, you have to print out the items in the array first, since when you don't know what's in it, there's no way to tell the result is correct.
- Base your code on the existing methods in the standard library because these are known to be thoroughly tested and work efficiently (I know, min/max looks like a too trivial example).
- I wouldn't bother too much about performance unless you really can show there is a performance problem in your code. Priority should be more like 1st correctness, 2nd readability/maintainability, 3rd performance.
- 制作静态方法。那些可以重复使用。
- 使用省略号 (...),因为这样您既可以像在代码中一样调用数组参数上的方法,也可以使用可变数量的参数作为
min(5,3,8,4,1)
. - 使用数据类型提供的最小/最大可能数字进行初始化
- 要检查您的代码是否有效,您必须首先打印出数组中的项目,因为当您不知道其中的内容时,就无法判断结果是否正确。
- 将您的代码基于标准库中的现有方法,因为众所周知,这些方法已经过彻底测试并且工作效率高(我知道,min/max 看起来太简单了)。
- 除非你真的能证明你的代码存在性能问题,否则我不会太在意性能。优先级应该更像是第一正确性,第二可读性/可维护性,第三性能。
Most of this has been already mentioned by others, but anyway, here's the code:
其他人已经提到了其中的大部分内容,但无论如何,这是代码:
import java.util.Random;
public class MinMax {
public static int min(int... args) {
int m = Integer.MAX_VALUE;
for (int a : args) {
m = Math.min(m, a);
}
return m;
}
public static int max(int... args) {
int m = Integer.MIN_VALUE;
for (int a : args) {
m = Math.max(m, a);
}
return m;
}
public static void main(String[] args) {
// fill an array with random numbers between 0 and 50
int[] ar = new int[10];
for (int i = 0; i < 10; i++)
{
ar[i] = new Random().nextInt(50);
System.out.println(ar[i]);
}
int maxValue = max(ar);
int minValue = min(ar);
System.out.println("The max is " + maxValue);
System.out.println("The min is " + minValue);
}
}
回答by Tomasz Nurkiewicz
Few tips:
小贴士:
Initialize
min
with first element and start from the second:int min = ar[0]; for(int i=1;i<10;i++)
...or start from:
int min = Integer.MAX_VALUE;
this approach is better if you expect your array can be empty.
Use
Math.min
to avoid explicit condition (some may say it's slower though):for(int i=0;i<10;i++) { min = Math.min(min, ar[i]); }
min
用第一个元素初始化并从第二个元素开始:int min = ar[0]; for(int i=1;i<10;i++)
...或从:
int min = Integer.MAX_VALUE;
如果您希望数组可以为空,这种方法会更好。
使用
Math.min
以避免明确的条件(有些人可能会说这是慢,虽然):for(int i=0;i<10;i++) { min = Math.min(min, ar[i]); }
回答by P.P
Initialize max to 0 & min to 50 won't work when the numbers change. A more appropriate way is:
1. initialize them to the first element of the array.
2. Use length
instead of a constant.
当数字改变时,将 max 初始化为 0 & min 为 50 将不起作用。更合适的方法是:
1. 将它们初始化为数组的第一个元素。
2. 使用length
代替常量。
max = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]>max)
{
max=ar[i];
}
}
Same for min:
分钟相同:
min = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]<min)
{
min=ar[i];
}
}
回答by Pankaj
public static void main(String[] args) {
int[] myArray = {9, 7,9, -40, -10, 40};
//int[] myArray = {};
//int[] myArray = {4};
System.out.println("Difference between max and min = "
+ findDifference(myArray));
}
// Find difference between Max and Min values for a given array
public static int findDifference(int[] arr) {
if (arr.length == 0) {
// Log
System.out.println("Input Array is empty");
return Integer.MIN_VALUE;
}
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
else if (arr[i] > max)
max = arr[i];
// Just to check if logic works fine
System.out.println("Min=" + min + " Max=" + max);
}
return max - min;
}
回答by anonymous
import java.io.*;
public class MultiDimensionalArrayIO {
public static void main(String[] args)throws IOException {
BufferedReader c= new BufferedReader (new InputStreamReader (System.in) );
System.out.print ( "Enter Number Column : " );
int column = Integer.parseInt(c.readLine());
System.out.print ( "Enter Number Row : " );
int row = Integer.parseInt(c.readLine());
int array [][] = new int [column][row];
int max = array [0][0];
int min = array [0][0];
int sum= 0;
for ( int i=0 ; i < array.length; i++){
for (int j=0 ; j<array[i].length; j++){
System.out.print("Enter Array Values ["+i+"]["+j+"]: " );
array[i][j]= Integer.parseInt (c.readLine());
min = Math.min(min , array[i][j]);
max = Math.max(max , array[i][j]);
sum += array[i][j];
}
}
System.out.println("The Min Number :"+ min);
System.out.println("The Max Number :"+ max+ " total is "+ sum);
}
}
回答by IsolaMonte
Depending on whether you'd want the max and min-functions in the same method you also have to consider the return type.
根据您是否希望在同一方法中使用 max 和 min 函数,您还必须考虑返回类型。
So far most suggestions have kept the two separate, meaning it's fine to return an int. However, if you put the max and min-functions into a findLargestDifference-method you'd have to return a long seeing as the largest difference between any given numbers in the int array can be the size of 2 ints. You'd also getting rid of having to loop over the int array twice.
到目前为止,大多数建议都将两者分开,这意味着返回一个 int 是可以的。但是,如果将 max 和 min 函数放入 findLargestDifference 方法中,则必须返回很长的时间,因为 int 数组中任何给定数字之间的最大差异可能是 2 个整数的大小。您还可以摆脱两次遍历 int 数组的麻烦。
Furthermore I recommend writing unit tests for corner and edge cases instead of printing in a main-method. It helps test your logic early on when implementing it and thus often makes the code cleaner.
此外,我建议为角落和边缘情况编写单元测试,而不是在主要方法中打印。它有助于在实现逻辑时尽早测试您的逻辑,因此通常会使代码更清晰。
See example code below.
请参阅下面的示例代码。
public class LargestDifference {
public static long find(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Input cannot be null or empty.");
}else {
long currentMax = numbers[0];
long currentMin = numbers[0];
for (int i=0; i < numbers.length; i++) {
if (currentMin > numbers[i]) {
currentMin = numbers[i];
}else if (currentMax < numbers[i]) {
currentMax = numbers[i];
}
}
return currentMax - currentMin;
}
}