Last active
August 26, 2017 16:03
-
-
Save MyGodIsHe/38a009e9511e1561099fdba34ec87f1d to your computer and use it in GitHub Desktop.
Golang functions to work with sorted array by binary search.
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 ( | |
"fmt" | |
"sort" | |
) | |
func OrderedInsert(a []int, j int) []int { | |
n := len(a) | |
if n == 0 { | |
return append(a, j) | |
} | |
i := sort.Search(n, func(i int) bool { return a[i] >= j }) | |
return append(a[:i], append([]int{j}, a[i:]...)...) | |
} | |
func OrderedSearch(a []int, j int) (int, bool) { | |
n := len(a) | |
i := sort.Search(n, func(i int) bool { return a[i] >= j }) | |
if i == n || a[i] != j { // not found | |
return 0, false | |
} | |
return i, true | |
} | |
func OrderedHas(a []int, j int) bool { | |
n := len(a) | |
i := sort.Search(n, func(i int) bool { return a[i] >= j }) | |
if i == n || a[i] != j { // not found | |
return false | |
} | |
return true | |
} | |
func OrderedDelete(a []int, i int) []int { | |
return append(a[:i], a[i+1:]...) | |
} | |
func main() { | |
var a []int | |
a = OrderedInsert(a, 1) | |
fmt.Println(a) | |
a = OrderedInsert(a, 5) | |
fmt.Println(a) | |
a = OrderedInsert(a, 3) | |
fmt.Println(a) | |
a = OrderedInsert(a, 2) | |
fmt.Println(a) | |
a = OrderedInsert(a, 4) | |
fmt.Println(a) | |
a = OrderedInsert(a, 0) | |
fmt.Println(a) | |
a = OrderedInsert(a, 6) | |
fmt.Println(a) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment