C ++线性搜索算法

时间:2013-12-14 03:31:37

标签: c++ arrays algorithm

我一直在努力研究线性搜索算法的输出一段时间。我有一个搜索列表并返回位置的函数,如果找不到,则返回-1,或者找到匹配数字的数值。有关如何正确输出的任何建议吗?

输出需要搜索testList,查看该数字是否在stdList中,并给出其位置

1号(34)位于第15位。

号码2(74)不在档案中。

号码3(56)不在档案中。

第4号(103)位于第75位。

以下是我遇到问题的代码的主要部分。

ARRAY_STANDARD指的是数组stdList的大小。

stdList是与

进行比较的数组

位置是函数searchList()

返回的内容

testList指的是与stdList

进行比较的数组

value是我们正在搜索的元素

//Outputs

  if (position == -1)
    cout << "Number " << testCount+1 << "(" <<  testList << ")" << " was not in the file." << endl;
  else
    cout << "Number " << testCount+1 << "(" <<  testList << ")" << " was located in position " << value << endl;
}

int searchList(int stdList [], int numElems, int value)
{
  int index=0;
  int position = -1;
  bool found = false;

  while (index < numElems && !found)
  {
    if (stdList[index] == value)
    {
      found = true;
      position = index;
    }
    index++; 
  }
  return position;
}

4 个答案:

答案 0 :(得分:1)

您似乎在上次编辑中丢失了几行代码。你想做什么(伪代码)是这样的:

for each element in testList:                <<<<< this is the for statement you lost
  position = findElement(element, stdList)   <<<<< this is the function you were not calling
  if(position < 0):
    print "not found"
  else:
    print "found element " element " at position " position

把它带走......

答案 1 :(得分:0)

您应该按照以下方式更改方法:

int searchList(int stdList [], int numElems, int value)
{
  int index=0;
  while (index < numElems)
  {
    if (stdList[index] == value)
    {
      return index;
    }
    index++; 
  }
  return -1;
}

答案 2 :(得分:0)

int searchList(int stdList [], int value)
{
    for(int i = 0, length = sizeof(stdList); i < length; ++i)
    {
        if (stdList[i] == value)
            return i;
    }
    return -1;
}

答案 3 :(得分:0)

成功输出。

int results;
for(int i = 0; i < 22; i++)
{
    results = searchList(stdList, ARRAY_STANDARD, testList[i]);
    if (results == -1)
        cout << "Number " << i+1 << "(" << testList[i] << ")" << " was not in the file." << endl;
    else
        cout << "Number " << i+1 << "(" << testList[i] << ")" << " was located in position " << results+1 << endl;
}