Built-in Methods
Rather than solving each and every problem manually, there are built-in methods available in programming languages which makes it easier for programmers to write code.
Let's have a look at the built-in methods available in Python, JavaScript, and Java to find the minimum and maximum value in an array.
- Python has built-in functions min() and max() to find the minimum and maximum value in an array.
- JavaScript has a built-in Math object that includes methods and constants for performing mathematical operations. We'll use Math.min() and Math.max() to find the minimum and maximum value in an array. Note that if we pass an array as an argument to these functions, it will return NaN. We can avoid this by using the spread operator to unwrap the elements.
- In Java, we can use Collections.min() and Collections.max() methods. But since this method requires a list, so first, we'll convert an array to a list and then pass the list to these functions as an argument.
Now let's have a look at examples using the built-in methods available in these languages:
xxxxxxxxxx
13
function findMinimumAndMaximum(input)
{
result = new Array();
result.maximum = Math.max(input);
result.minimum = Math.min(input);
return result;
}
const input = [1,4,100,9,456];
result = findMinimumAndMaximum(input);
document.write("Minimum value in an array is ",result.minimum);
document.write("Maximum value in an array is ",result.maximum);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment