使用Divide and Conquer搜索char数组中的字符串

时间:2015-06-18 08:44:01

标签: c++ c arrays divide-and-conquer

让我们说我有一个struct数组,每个元素都有一个名字。像:

struct something{
  char name[200];
}a[NMAX];

给定一个新字符串(char数组),我需要使用分而治之找到正确的索引。像:

char choice[200];
cin>>chioce;
int k=myFunction(choice);  // will return the index, 0 otherwise
                           // of course, could be more parameters
if( k )  
 cout<<k;

我不知道如何创建搜索功能(我试过,我知道D&amp; C是如何工作的,但我还在学习!)。

不,我不想使用字符串!

这是我试过的:

int myFunction(char *choice, int l,int r)   // starting with l==0 && r==n-1
{
    int m;
    if(strcmp(a[m].name,choice)==0)
            return m;
    else{
            m=(l+r)/2;
            return myFunction(choice,l,m-1);
            return myFunction(choice,m+1,r);
    }
}

1 个答案:

答案 0 :(得分:2)

这是我针对您上述问题的解决方案。但我在你的代码中修改了一些东西。

#include<iostream>
using namespace std;

#define NMAX 10

struct something{
  char *name; //replaced with char pointer so that i can save values the way i have done
}a[NMAX];

int myFunction(char *choice, int l,int r)   // starting with l==0 && r==NMAX-1
{
    if(l>r) //return if l has become greater than r
        return -1;
    int m=(l+r)/2;

    if(strcmp(a[m].name,choice)==0)
            return m+1;
    else if(l==r) //returned -1 as the value has not matched and further recursion is of no use
                return -1;
    else{

            int left= myFunction(choice,l,m-1);//replaced return
            int right= myFunction(choice,m+1,r);//by saving values returned
            if(left!=-1)                      //so that i can check them,
                return left;                  //otherwise returning from here onlywould never allow second satatement to execute
            if(right!=-1)
                return right;
            else
                return -1;
    }
}

int main(){

a[0].name="abc";
a[1].name="a";
a[2].name="abcd";
a[3].name="abcf";
a[4].name="abcg";
a[5].name="abch";
a[6].name="abcj";
a[7].name="abck";
a[8].name="abcl";
a[9].name="abcr";
char choice[200];
cin>>choice;
int k=myFunction(choice,0,NMAX-1);  // will return the index, 0 otherwise
                           // of course, could be more parameters
if( k !=-1)
 cout<<k;
 else
    cout<<"Not found";
return 0;
}

希望它会有所帮助。