[Home]
[Contents]
[Chapter]
[Previous Algorithm]
[Next Algorithm]


Prefix searching in a PAT array


int search( pat, index, n ) char *pat, *index[]; int n; /* size of the PAT array */ { int m, left, right, low, high, i; m = strlen(pat); /* search left end */ if( strncmp( pat, index[0], m ) != 1 ) left = 0; else if( strncmp( pat, index[n-1], m ) == 1 ) left = n; else { /* binary search */ for( low=0, high=n; high-low > 1; ) { i = (high+low)/2; if( strncmp( pat, index[i], m ) != 1 ) high = i; else low = i; } left = high; } /* search right end */ if( strncmp( pat, index[0], m ) == -1 ) right = -1; else if( strncmp( pat, index[n-1], m ) != -1 ) right = n-1; else { /* binary search */ for( low=0, high=n; high-low > 1; ) { i = (high+low)/2; if( strncmp( pat, index[i], m ) != -1 ) low = i; else high = i; } right = low; } return( right-left+1 ); }

C source (724.srch.c)



© Addison-Wesley Publishing Co. Inc.