Created
April 30, 2015 09:38
-
-
Save zhum/57cb45d8bbea86d87490 to your computer and use it in GitHub Desktop.
Golang function to insert in sorted array
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
// Mytype must implement Less func. | |
func SortedInsert (s []Mytype, f Mytype) []Mytype { | |
l:=len(s) | |
if l==0 { return [f] } | |
i := sort.Search(l, func(i int) bool { return s[i].Less(f)}) | |
if i==l { // not found = new value is the smallest | |
return append([f],s) | |
} | |
if i==l-1 { // new value is the biggest | |
return append(s[0:l],f) | |
} | |
return append(s[0:l],f,s[l+1:]) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another solution without conditionals (not needed, works on arrays of any size, including empty) and Less function
Go playground example