[ 簡単な説明 ]
探索要素の型毎のバイナリ探索関数を定義しています。
探索要素がない場合は,−1を返します。 |
/* search.c 探索ルーチン */ #include "match.h" int bsrch_i(int srch, int a[], int n) { int p; int s, s1, s2; if(*a == srch) return 0; if(*(a + n - 1) == srch) return n - 1; s1 = 0; s2 = n - 1; while(1) { if((p = *(a + (s = (s1 + s2) / 2))) == srch) return s; if(s2 - s1 < 2) return -1; if(p > srch) s2 = s; else s1 = s; } } int bsrch_d(double srch, double a[], int n) { double p; int s, s1, s2; if(*a == srch) return 0; if(*(a + n - 1) == srch) return n - 1; s1 = 0; s2 = n - 1; while(1) { if((p = *(a + (s = (s1 + s2) / 2))) == srch) return s; if(s2 - s1 < 2) return -1; if(p > srch) s2 = s; else s1 = s; } } int bsrch_c(unsigned char *srch, unsigned char *a[], int n) { int cmp, s, s1, s2; if(strcmp(*a, srch) == 0) return 0; if(strcmp(*(a + n - 1), srch) == 0) return n - 1; s1 = 0; s2 = n - 1; while(1) { cmp = strcmp(*(a + (s = (s1 + s2) / 2)), srch); if(cmp == 0) return s; if(s2 - s1 < 2) return -1; if(cmp > 0) s2 = s; else s1 = s; } } |