Golang : Find smallest number in array
Alright, today I'll just write this simple tutorial on how to find the smallest value in an array. Basically, the algorithm is just iterate through the values inside the given array and replace the final value( which is the variable min) with the smallest value it can find.
Here's the code :
package main
import "fmt"
func main() {
arr := []uint{
28, 33, 16,
7, 5, 88,
}
min := arr[0] // assume first value is the smallest
for _, value := range arr {
if value < min {
min = value // found another smaller value, replace previous value in min
}
}
fmt.Println("The smallest value is : ", min)
}
Output :
The smallest value is : 5
See also : Golang : Find biggest/largest number in array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6k Golang : Debug with Godebug
+25.1k Golang : Storing cookies in http.CookieJar example
+3.2k Golang : Fix go-cron set time not working issue
+4.6k Unix/Linux : How to pipe/save output of a command to file?
+41.5k Golang : How do I convert int to uint8?
+5k Golang : Customize scanner.Scanner to treat dash as part of identifier
+9.3k Golang : Convert(cast) string to int64
+11.8k Golang : Clean formatting/indenting or pretty print JSON result
+5.3k Golang : fmt.Println prints out empty data from struct
+23k Golang : Randomly pick an item from a slice/array example
+12.3k Golang : Search and extract certain XML data example
+37.5k Golang : Comparing date or timestamp