c2go
c2go copied to clipboard
Implement bsearch()
Depends on #157 Support function pointers
Documentation http://www.cplusplus.com/reference/cstdlib/bsearch/
C example:
/* bsearch example */
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort, bsearch, NULL */
int compareints (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int values[] = { 50, 20, 60, 40, 10, 30 };
int main ()
{
int * pItem;
int key = 40;
qsort (values, 6, sizeof (int), compareints);
pItem = (int*) bsearch (&key, values, 6, sizeof (int), compareints);
if (pItem!=NULL)
printf ("%d is in the array.\n",*pItem);
else
printf ("%d is not in the array.\n",key);
return 0;
}
Go:
/* bsearch example */ //
//
func compareints(a interface{}, b interface{}) int {
return ((a.([]int))[0] - (b.([]int))[0])
}
var values []int = []int{50, 20, 60, 40, 10, 30}
// main - transpiled function from /home/konstantin/go/src/templorary/7.c:12
func main() {
var pItem []int
var key int = 40
sort.SliceStable(values, func(i, j int) bool {
c2goTempVarA := ([]int{values[i]})
c2goTempVarB := ([]int{values[j]})
return compareints(c2goTempVarA, c2goTempVarB) <= 0
})
pItem = bsearch((*[1]int)(unsafe.Pointer(&key))[:], values, size_t(6), size_t((4)), compareints).([]int)
if pItem != nil {
noarch.Printf([]byte("%d is in the array.\n\x00"), pItem[0])
} else {
noarch.Printf([]byte("%d is not in the array.\n\x00"), key)
}
return
}
func init() {
stdin = noarch.Stdin
stdout = noarch.Stdout
stderr = noarch.Stderr
}
function bsearch
is not implemented.