If you want to get the biggest and smallest element, not its value, you could just do the for
.
func MinMax(v []int) (posMin int, posMax int) {
max, min := 0, int((^uint(0)) >> 1)
for i, e := range v {
if e > max {
max, posMax = e, i
}
if e < min {
min, posMin = e, i
}
}
return
}
So the result would be:
slice := []int{122, 992, 130, 250, 100, 200, 202, 103, 923, 555, 674, 893}
fmt.Print(MinMax(slice))
4 1
The function has the function of returning the position, not the value, since its question says "find the smallest and largest element". Finally, the result of the above function, 4 1
, would indicate that slice[4]
is the lowest value and the slice[1]
is the greatest.
If the amount of data is too large, I believe I can divide Lice among goroutines. Keeping the simplicity of the comparison, it would be enough to divide len(slice) / QuantidadeDeThreads
, then supposing it has 100 elements and 4 threads would have 25 elements for each goroutine: the first would compare only 0~24, the next 25~49 (...). Then, finally, compare the result of each goroutine.
You can add this function as non-exported and/or create a Internal package.
Another alternative would be Sort, but could only obtain the minimum/maximum value:
slice := []int{122, 992, 130, 250, 100, 200, 202, 103, 923, 555, 674, 893}
sorted := sort.Ints(slice)
l := len(sorted)
if l == 0 {
return
}
min, max := sorted[0], sorted[l - 1]
You can try using the function
Ints
standard packagesort
. Here you find the documentation.– Guto