題組內容
三、C 語言函式原型 int search(int A[], int n, int x);
的第一個參數為整數陣列 A[] 第二個參數為整數 n 代表搜尋範圍為索引從 0 到 n - 1 , 。 若存在一個不為負而且小於 n 的整數 i,滿足 A[i]等於第三個參數整數 x,則函式回 傳值為 i,否則函式回傳值等於-1。假如有多個 i 值滿足條件,則函式回傳值為最大 的 i。 (每小題 20 分,共 40 分)
⑴請以遞迴的(recursive)循序搜尋(sequential search)法撰寫這個函式。
詳解 (共 3 筆)
詳解
int search(int *A, int n, int x) {
if(n == 0) return(-1);
else if(x == A[n-1]) return(n-1);
else return(search(A, n-1, x));
}
詳解
在C語言中,使用遞迴實現循序搜尋可以按照以下方式進行。我們將實現一個遞迴函式來尋找目標值x在陣列A[]中的最大索引位置。如果找到多個符合的元素,將回傳最大的索引;如果沒有找到,則回傳-1。
考慮到函式原型為int search(int A[], int n, int x);,下面是按要求實現的遞迴版本:
#include <stdio.h>
int searchRecursive(int A[], int n, int x, int currentIndex) {
// 如果當前索引超出範圍,返回-1表示未找到
if (currentIndex < 0) return -1;
// 如果當前索引超出範圍,返回-1表示未找到
if (currentIndex < 0) return -1;
// 如果找到目標值
if (A[currentIndex] == x) return currentIndex;
if (A[currentIndex] == x) return currentIndex;
// 否則,在剩餘的陣列中繼續尋找
return searchRecursive(A, n, x, currentIndex - 1);
}
return searchRecursive(A, n, x, currentIndex - 1);
}
int search(int A[], int n, int x) {
// 從陣列的末尾開始遞迴搜索
return searchRecursive(A, n, x, n - 1);
}
// 從陣列的末尾開始遞迴搜索
return searchRecursive(A, n, x, n - 1);
}
int main() {
int A[] = {1, 2, 3, 4, 5, 6, 3};
int n = sizeof(A) / sizeof(A[0]);
int x = 3;
int A[] = {1, 2, 3, 4, 5, 6, 3};
int n = sizeof(A) / sizeof(A[0]);
int x = 3;
int result = search(A, n, x);
if (result != -1) {
printf("Element %d found at index %d\n", x, result);
} else {
printf("Element %d not found in the array\n", x);
}
if (result != -1) {
printf("Element %d found at index %d\n", x, result);
} else {
printf("Element %d not found in the array\n", x);
}
return 0;
}
這個例子中,searchRecursive是一個輔助函式,用於執行實際的遞迴搜索。我們從陣列的末尾(n-1索引處)開始向前搜索,這樣可以保證如果有多個符合的元素,我們最終回傳的是最大的索引值。search函式是公開接口,接受陣列A[]、陣列長度n和目標值x作為參數,並調用searchRecursive函式來完成搜索任務。
}
這個例子中,searchRecursive是一個輔助函式,用於執行實際的遞迴搜索。我們從陣列的末尾(n-1索引處)開始向前搜索,這樣可以保證如果有多個符合的元素,我們最終回傳的是最大的索引值。search函式是公開接口,接受陣列A[]、陣列長度n和目標值x作為參數,並調用searchRecursive函式來完成搜索任務。
這種實現方式既展示了遞迴的使用,也符合了題目要求的功能。
詳解
int search(int A[],int m,int x) { int i; while(i>=0 & i