[Example 6-25] finds the specified string for a sorted array of character pointers. The strings are arranged in dictionary order, and the lookup algorithm uses a binary method, or is called a binary lookup. Binary Lookup Algorithm Description:
1. Set the N-string into an array of pointers by opening (or descending) order.
2. Set low to point to the lower end of the array of pointers, high point pointer array of high-end, mid= (Low+high)/2
3. Test whether the string referred to in mid is the string you are looking for.
4. In dictionary order, mid refers to strings larger than the string to look up, which indicates that the string is being searched between low and mid, otherwise, it indicates the string being searched between mid and high.
5. Modify the value of low type High, recalculate mid, continue to search.
#include <stdlib.h>
#include <alloc.h>
#include <string.h>
#include <stdio.h
Main ()
{
char *binary ();/* Function declaration */
Char *ptr1[5],*temp;
int i,j;
for (i=0;i<5;i++)
{
Ptr1[i]=malloc (20);////* Enter string in dictionary order */
Gets (Ptr1[i]);
}
printf ("\ n");
printf ("Original string:\n");
for (i=0;i<5;i++)
printf ("%s\n", Ptr1[i]);
printf ("Input search string:\n");
Temp=malloc;
Gets (temp);/input is lookup string */
I=5;
Temp=binary (ptr1,temp,i);/* Call lookup function */
if (temp) printf ("succesful-----%s\n", temp);
Else printf ("nosuccesful!\n");
return;
}
Char *binary (char *ptr[],char *str,int fixed n) returns the function of the character pointer */
{/* binary lookup */
int hig,low,mid;
Low=0 n-1;
while (Low<=hig)
{
mid= (low+hig)/2;
if (strcmp (str,ptr[mid)) <0)
Hig=mid-1;
Else if ( strcmp (Str,ptr[mid]) >0)
Low=mid+1;
Else return (str);/* Audit success, return the searched String */
}
returns null;/* lookup failed, returning NULL pointer */
}