Array of pointers (ii)

Source: Internet
Author: User
Tags array printf strcmp

[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 */
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.