C++线性搜索算法

C++ Linear search algorithm

本文关键字:搜索算法 线性 C++      更新时间:2023-10-16

我正试图在c++上创建一个线性搜索算法,但我的代码中的linearSearch函数遇到了一些问题。这是一个简单的for循环,我看不出问题出在哪里,我要求用户输入一个键,如果它是数组中的键,那么它应该给出正确的位置,但它没有。有人能看到我在实现中哪里出了问题吗?

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int linearSearch(int arr[],int size, int key){
for(int i = 0; i < size; ++i){
    if(key == arr[i]){
        return i;
    }else{
        return -1;
    }
  }
}

int main() {
 const int size = 20;
 int numbers[size];
 srand((unsigned) time(0));
 for(int i = 0; i < size; ++i){
    numbers[i] = (rand() % 100) + 1;
    cout << numbers[i] << " ";
 }
 cout << endl;
 int key;
 cout << "Enter a key to search for: " << endl;
 cin >> key;
 int retValue = linearSearch(numbers,size,key);
 if(retValue >= 0){
     cout << "Key found at position " << retValue << endl;
 }else{
     cout << "Key not found" << endl;
 }
return 0;
}

问题就在这里:

if(key == arr[i]){
     return i;
 }else{
     return -1;
 }

在第一次比较后返回i或-1,因此根本不会搜索数组的其余部分。您应该仅在函数末尾删除else return -1子句和return -1

如果这样做,linearSearch函数应该看起来像:

int linearSearch(int arr[],int size, int key){
    for(int i = 0; i < size; ++i){
        if(key == arr[i]){
           return i;
        }
    }
    return -1;
}

linearSearch函数的问题是,如果不匹配,它在第一次比较后立即返回-1(未找到(。它不会搜索整个数组。

请尝试以下代码,该代码向后搜索,并在发现重合或传递数组的"底部"时停止(i等于-1(。它返回i的当前值,如果满足重合度,则可以将其放入数组中;如果搜索过程中没有发生任何事情,则返回-1。

int linearSearch(int arr[], int size, int key){
    int i;
    for(i = size-1; i >= 0 && key != arr[i]; --i);
    return i;
}
int linearSearch(int array[], int n,int searchKey){
    for(int i=0; i<n;i++){
        if(searchKey==array[i]){
        return i;
        }
    }
    return -1;
}
int linearSearch(int arr[], int size, int key) {
    for (int i = 0; i < size; i++) {
        if (arr[i]==key) {
            return i;
        }
    }
    return -1;
}

问题是您要么返回i,要么返回-1,否则什么都不返回。代码将在返回这两个之后退出。并且我还认为CCD_ 6也随着CCD_。