使用 C 語言實現的 linearSearch 遞迴函數。這個函數將遍歷給定陣列的一個範圍(從 start 到 end),尋找匹配的 key 值。如果找到了 key,函數返回 key 在陣列中的位置;如果沒找到,返回 -1。
c
Copy code
#include <stdio.h>
// 函數聲明
int linearSearch(int key, int data[], int start, int end);
int main() {
int data[] = {3, 6, 8, 12, 14, 17, 25, 29, 31, 36, 42, 47, 53, 55, 62};
int n = sizeof(data) / sizeof(data[0]);
int key = 31;
// 呼叫 linearSearch 函數
int result = linearSearch(key, data, 0, n-1);
if (result != -1) {
printf("元素 %d 出現在陣列的位置:%d\n", key, result);
} else {
printf("元素 %d 未在陣列中找到。\n", key);
}
return 0;
}
// 函數定義
int linearSearch(int key, int data[], int start, int end) {
// 如果結束位置小於起始位置,表示範圍無效,返回 -1
if (end < start) {
return -1;
}
// 檢查起始位置的元素是否是搜尋鍵
if (data[start] == key) {
return start;
}
// 否則,遞迴調用函數本身,對範圍中的下一個元素進行檢查
return linearSearch(key, data, start + 1, end);
}
在這個實現中,linearSearch 函數會遞迴地檢查每個元素,直到找到匹配的元素或者檢查完所有元素。這種方法雖然簡單易懂,但在大型數據集上可能不是最高效的搜索策略,特別是對於已排序的數據集,二分搜尋法(Binary Search)會是更好的選擇。然而,對於未排序的數據集或需要執行少量搜尋操作的情況,線性搜尋是一種實用的解決方案。