ModularM
Modular2y ago
19 replies
bunny

sort with custom `cmp_fn`

In Go, I can easily sort a slice with something like:
sort.Slice(my_slice, func(i, j int) bool {
    return my_slice[i][2] < my_slice[j][2]
})


The portion func(i, j int) bool { return my_slice[i][2] < my_slice[j][2] } is an anonymous function (lambda) that is used to determine sort order. Therefore, that quick one-liner (3-liner for readibility) will sort based on the value of index
2
. As a result, if my_slice starts as:
[ [1, 2, 1], [2, 3, 9], [3, 4, 5] ]
then it will sort to:
[ [1, 2, 1], [3, 4, 5], [2, 3, 9] ]

Looking at the doc page for algorithm.sort, it appears to take a cmp_fn arg (like the above anonymous function). Does anybody have sample code I can peek at for how to actually implement? ...tiny brain is confused. 😊
Was this page helpful?