Sha256: 2c3e25cc7e3919461dc0e234882cf7034b2f1c4c101dcaf73ba0503cd7667778

Contents?: true

Size: 595 Bytes

Versions: 1

Compression:

Stored size: 595 Bytes

Contents

#include <ruby.h>

static ID id_cmp;

static VALUE rb_array_binary_index(VALUE self, VALUE value) {
  int lower = 0;
  int upper = RARRAY(self)->len - 1;
  int i, comp;

  while(lower <= upper) {
    i = lower + (upper - lower) / 2;
    comp = FIX2INT(rb_funcall(value, id_cmp, 1, RARRAY(self)->ptr[i]));

    if(comp == 0) {
      return LONG2NUM(i);
    } else if(comp == 1) {
      lower = i + 1;
    } else {
      upper = i - 1;
    };
  }
  return Qnil;
}

void Init_binary_search() {
  id_cmp = rb_intern("<=>");
  rb_define_method(rb_cArray, "binary_index", rb_array_binary_index, 1);
}

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tyler-binary_search-0.1.0 ext/binary_search.c