find the kth smallest key in a map in go

Here's an example code snippet in Go to find the kth smallest key in a map using sorting and the algorithm package:

main.go
import (
    "fmt"
    "sort"
)

func findKthSmallestKey(m map[int]string, k int) int {
    var keys []int
    for k := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)
    return keys[k-1]
}

func main() {
    m := map[int]string{
        3: "three",
        1: "one",
        4: "four",
        2: "two",
    }
    k := 2
    kthSmallestKey := findKthSmallestKey(m, k)
    fmt.Printf("The %dth smallest key in map %v is %d\n", k, m, kthSmallestKey)
}
471 chars
26 lines

In this example, we first iterate over the keys of the map and add them to slice keys. We then sort the slice in ascending order, and return the k-1th element (zero-indexed, so k-1 rather than k). Finally, we call findKthSmallestKey with our map and the value of k we want to find, and print out the result.

gistlibby LogSnag