In Go, we can import libraries with built-in functions for finding an array's maximum and minimum elements. For example, the sort package offers sorting functions, which can be used to obtain the maximum and minimum values directly.
Alternatively, we can implement our custom function to find the maximum and minimum elements by iterating over the array and comparing the elements. This approach allows us to define our comparison logic and criteria for determining the maximum and minimum values.
Let's delve into two distinct Go examples. The first example demonstrates how to use the sort package to find the maximum and minimum values. In the second example, we'll make our own function to achieve the same result.
We can use sort to make the array in ascending order and then pick the first and last element to get the max and min of the array.
package mainimport ("fmt""sort")func main() {array := []int{9, 5, 7, 2, 1, 6, 8, 3, 4}sort.Ints(array)minimum := array[0]maximum := array[len(array)-1]fmt.Println("Minimum:", minimum)fmt.Println("Maximum:", maximum)}
Line 10: It sorts the array in ascending order to help find the max and min.
Line 11: As the array is sorted, we can pick the first element by indexing the array at 0. This value will be the minimum.
Line 12: Similarly, the maximum value will be at the last index, so we will pick the element that is going to be at the index len(array)-1
In this approach, we assign the first element as the initial maximum and minimum. Then, we iterate through the remaining elements, updating the maximum and minimum values whenever a value lower than the current minimum or higher than the current maximum is encountered.
package mainimport ("fmt")func findMaxMin(arr []int) (int, int) {// Initialize the variables to hold the maximum and minimum values to draw comparisons.max := arr[0]min := arr[0]// Iterate over the arrayfor i := 1; i < len(arr); i++ {// if the current element is greater than the present maximumif arr[i] > max {max = arr[i]}// if the current element is smaller than the present minimumif arr[i] < min {min = arr[i]}}return max, min}func main() {// Examplearray := []int{9, 5, 7, 2, 1, 6, 8, 3, 4}maximum, minimum := findMaxMin(array)fmt.Println("Minimum:", minimum)fmt.Println("Maximum:", maximum)}
Line 7: The findMaxMin()
the function takes an integer array as input and returns the maximum and minimum values.
Lines 8–9: It initializes the max
and min
variables with the first element of the array and then iterate over the remaining elements using a for
loop.
Lines 14–16: If an element is found that is greater than the current maximum, it updates the max
variable.
Lines 19–21: Similarly, if an element is found that is smaller than the current minimum, it updates the min
variable.
We can find the maximum and minimum values in Go within a time complexity of
Free Resources