Skip to content

Instantly share code, notes, and snippets.

@zhum
Created April 30, 2015 09:38
Show Gist options
  • Save zhum/57cb45d8bbea86d87490 to your computer and use it in GitHub Desktop.
Save zhum/57cb45d8bbea86d87490 to your computer and use it in GitHub Desktop.
Golang function to insert in sorted array
// 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:])
}
@mantaspet
Copy link

Another solution without conditionals (not needed, works on arrays of any size, including empty) and Less function

func insertSort(data []Example, el Example) []Example {
	index := sort.Search(len(data), func(i int) bool { return data[i].field > el.field })
	data = append(data, Example{})
	copy(data[index+1:], data[index:])
	data[index] = el
	return data
}

Go playground example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment