Created
May 18, 2017 13:05
-
-
Save danielrangelmoreira/33b9b0686ac4e2ee2cb5f75a9896b28f to your computer and use it in GitHub Desktop.
Insert items in a sorted slice/array (golang)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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