【问题标题】:C: Binary Search for Char (name)C:对 Char(名称)进行二分搜索
【发布时间】:2015-04-01 11:22:44
【问题描述】:

我在理解如何对 char 进行二进制搜索时遇到问题。我必须搜索智能手机的名称。我有这个:

typedef struct smartphone {
    char name[50];
    double weight;
} smartphone;

smartphone smartphone[50];
char smartphone_searched = "Xperia U";

所以,我必须对名称“Xperia U”进行二分搜索。有什么建议?

【问题讨论】:

  • 不能在 char 变量中保存字符串。

标签: c search binary char


【解决方案1】:

首先,您需要根据智能手机的名称对数组进行排序(使用二进制搜索),如下所示:

for(int i=0; i<49; i++)
{
    int minIndex = i;
    for(int j=i+1; j<50; j++)
    {
        if(strcmp(smartphone[i].name, smartphone[j].name) > 0)
            minIndex = j;
    }
    smartphone tmp = smartphone[i];
    smartphone[i] = smartphone[minIndex];
    smartphone[minIndex] = tmp;
}

然后,您将使用 strcmp 使用二进制搜索逻辑来找到答案。

【讨论】:

    【解决方案2】:

    纠错:

     char smartphone_searched[50] = "Xperia U";
    

    而不是

    char smartphone_searched = "Xperia U";
    

    然后使用 qsort() 将结构数组排序为:

    static int cmp(const void *p1, const void *p2)
    {
            char* y1 = ((const struct smartphone*)p1)->name;
            char* y2 = ((const struct smartphone*)p2)->name;
    
            if (strcmp(y1,y2) > 0)
                return -1;
            else
                return 1;
    }
    

    然后

    qsort(smartphone, 50, sizeof(*smartphone), cmp);
    

    然后对数组使用二进制排序

    int i=0;
    int j=49;
    while(i<j)
    {
        mid=i+j;
        if(strcmp(smartphone[mid],smartphone_searched)==0)
        {
              printf("Found\n);
              return 0;
        }
        else if(strcmp(smartphone[mid],smartphone_searched)>0)
               i=mid+1;
        else
               j=mid-1;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 2014-03-02
      • 1970-01-01
      • 2021-11-30
      • 2020-12-16
      • 2016-01-19
      • 2017-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多