find the smallest element in an array in go

To find the smallest element in an array in Go, you can iterate over the entire array and keep track of the smallest element seen so far. This can be achieved by initializing the smallest element variable with the first element of the array and updating it whenever a smaller element is encountered.

Here's an implementation of this approach:

main.go
func findSmallestElement(arr []int) int {
    if len(arr) == 0 {
        return -1 // handle empty array case
    }

    min := arr[0]
    for _, num := range arr {
        if num < min {
            min = num
        }
    }

    return min
}
244 chars
15 lines

This function takes an integer array arr as input and returns the smallest element in the array. If the array is empty, it returns -1 to indicate an error.

We initialize min to be the first element of the array arr. Then, we iterate over each element of the array and update min if a smaller element is encountered.

You can call this function like this:

main.go
arr := []int{2, 4, 1, 7, 5}
smallest := findSmallestElement(arr)
fmt.Println("Smallest element is", smallest)
110 chars
4 lines

Output:

main.go
Smallest element is 1
22 chars
2 lines

related categories

gistlibby LogSnag