C++线性搜索算法
C++ Linear search algorithm
我正试图在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_。
相关文章:
- std::unordered_map 搜索算法是如何实现的?
- C++线性搜索算法,确定数组中元素的数量
- 对于具有引用返回类型的搜索算法,默认返回值应该是什么?
- 使用迭代深度优先搜索算法的未加权图的最短路径
- 尝试实现二叉搜索算法,似乎无法使其工作
- 图上的深度优先搜索算法中的内存泄漏
- 使用图形的字符串搜索算法?C++
- 使用 while 循环和搜索算法进行复制
- C++ 循环和搜索算法,重复
- 了解一种神秘地起作用的递归二进制搜索算法
- 双二叉搜索算法
- 修改广度优先搜索算法以记住矩阵中的最短路径
- C 搜索算法第一个数字= n
- 如何在较高和较低数字的阵列中适应搜索算法(3N / 2)-2
- C++线性搜索算法
- 为什么排序调用比较函数的频率低于线性最小搜索算法
- 线性搜索算法
- C++ 数组上的线性搜索算法
- 如何创建一个线性搜索算法比我的教科书提供的更容易
- C++线性搜索算法