c2go icon indicating copy to clipboard operation
c2go copied to clipboard

Implement bsearch()

Open elliotchance opened this issue 7 years ago • 3 comments

elliotchance avatar Aug 19 '17 07:08 elliotchance

Depends on #157 Support function pointers

yulvil avatar Oct 19 '17 00:10 yulvil

Documentation http://www.cplusplus.com/reference/cstdlib/bsearch/

Konstantin8105 avatar Jan 09 '18 13:01 Konstantin8105

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.

Konstantin8105 avatar Feb 16 '18 12:02 Konstantin8105