[英]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
否則什么都沒有。 返回這兩個后代碼將退出。 而且我還認為retValue
也可以增加1
以獲得正確的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.