OneBite.Dev - Coding blog in a bite size

find the minimum and maximum element in an array in Go

Code snippet on how to find the minimum and maximum element in an array in Go

func minMax(arr []int) (int, int) {
  min, max := arr[0], arr[0]
  for _, v := range arr {
    if v < min {
      min = v
    }
    if v > max {
      max = v
    }
  }
  return min, max
}

This code finds the minimum and maximum elements within an array. It begins by assigning the value of the first element in the array as both the minimum and maximum. It then iterates through all the elements in the array and compares each one with the current minimum and maximum. If the current element is smaller than the current minimum, it assigns the current element as the new minimum. Similarly, if it is larger than the current maximum, it assigns the current element as the new maximum. Finally, it returns the minimum and maximum.

go