蛮力算法02

——找东西,是个很重要的命题。

 

顺序查找和字符串匹配也是蛮力求解的典范。

 

顺序查找

template<typename ObjectType>
int Find( ObjectType *arr,int arrLen,ObjectType findItem )
{
    for (int i=0;i<arrLen;++i)
    {
        if (arr[i] == findItem)
        {
            return i;
        }
    }
 
    return -1;
}

 

 

字符串蛮力匹配

RandomCreate rd;
ConsoleOutput<char> output;
 
//65,123
const int ARR_SOURCE_LEN = 20;
const int ARR_FIND_LEN = 1;
char sourceArr[ARR_SOURCE_LEN];
char findArr[]={'c'};
 
rd.RandomChars(sourceArr,ARR_SOURCE_LEN,97,123);
 
cout<<"要查找的源字符串: "<<endl;
output.OutputArray(sourceArr,ARR_SOURCE_LEN);
 
cout<<"要查找的串:"<<endl;
output.OutputArray(findArr,ARR_FIND_LEN);
 
int findIndex = -1;
for (int i=0;i<ARR_SOURCE_LEN-ARR_FIND_LEN;++i)
{
    int j=0;
    for (;j<ARR_FIND_LEN;++j)
    {
        if (sourceArr[i+j] != findArr[j])
        {
            break;
        }
    }
    if (j == ARR_FIND_LEN)
    {
        findIndex = i;
        break;
    }
}
 
cout<<"查找结果是: "<<findIndex<<endl;
posted @ 2012-08-28 22:00  sharpfeng  阅读(308)  评论(0编辑  收藏  举报