Skip to content

Instantly share code, notes, and snippets.

@danielrangelmoreira
Created May 18, 2017 13:05
Show Gist options
  • Save danielrangelmoreira/33b9b0686ac4e2ee2cb5f75a9896b28f to your computer and use it in GitHub Desktop.
Save danielrangelmoreira/33b9b0686ac4e2ee2cb5f75a9896b28f to your computer and use it in GitHub Desktop.
Insert items in a sorted slice/array (golang)
package main
import "sort"
import "fmt"
func main() {
data := []int{20, 21, 22, 24, 25, 26, 28, 29, 30, 31, 32}
var items = []int{23, 27}
for _, x := range items {
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i < len(data) && data[i] == x {
fmt.Println(i)
} else {
data = append(data, 0)
copy(data[i+1:], data[i:])
data[i] = x
}
fmt.Println(data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment