How to find the largest and smallest element of an Array/Slice in Go?

Asked

Viewed 317 times

-1

Hi, guys!

I would like some help. How could I find the smallest and largest element of an Array/Slice in Go? Is there a standard library function that already does this? If not, could you show me the way to implement an algorithm to solve this problem.

Ex:

numeros := []int{
    122, 992, 130, 250,
    100, 200, 202, 103,
    923, 555, 674, 893,
}

In my case I would have to find the smallest and largest number from a list of numbers about 500 MB. If you have standard library function references to work with Arrays/Slices, please send me.

  • You can try using the function Ints standard package sort. Here you find the documentation.

1 answer

0

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]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.