2.1 Searching

Linear search

One way to know how many element are in the array is to pass the length as an argument; another is to place a NULL marker at the end of the array:

// lookup: sequential search for word in array
int lookup(char *word, char *array[])
{
     int i;
     for(i=0; array[i] != NULL;i++)
          if(strcmp(word, array[i])==0)
            return i;
     return -1;
}
Binary search

For binary search, the table must be sorted,and we must know how long the table is .The NELEMS macro we wrote before can help.
Here is an excerpt.

printf("the HTML table has %d words\n", NELEMS(htmlchars));
// Binary search for name in tab; return index
int lookup(char *name, Nameval tab[], int ntab)
{
   int low,high,mid,cmp;
   low=0;
   high=ntab-1;
   while(low <=high){
       mid=(low+high)/2;
       cmp=strcmp(name,tab[mid].name);
       if(cmp<0)
          high=mid-1;
       else if (cmp  >0)
          low=mid+1;
       else
          return mid; //found match
   }
 return -1; //no match; 
}  

Binary search is faster than linear search especially when you have a large size of input. Ignoring roundoff, the proportion is log2n.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 厉害了我的室友亲!北漂半年,合租自如,岂料今晚差点丢掉小命!新室友两次忘关煤气,差点熏死,幸得我这个吃货半夜去厨房...
    甜不辣田心小姐阅读 1,566评论 0 0
  • 时间管理可谓是当下最“网红”的词语了。经常能听到很多人在谈时间管理。之前我一直认为最高效的时间管理就是专心的做好每...
    小小青橙阅读 1,911评论 2 1
  • 这十几天感觉自己又颓废了,一天到晚过得乱七八糟,心里越乱,越理不出头绪,越理不出头绪就越无从下手,越无从下手就越没...
    xz蓝天阅读 2,744评论 1 4