使用疊代(iterative)方法來實現循序搜尋的函式,可以直接通過一個循環來遍歷陣列中的所有元素,從而尋找目標值x。如果存在多個符合條件的索引i,根據題目要求,我們應該返回最大的i值。如果沒有找到,則返回-1。
這裡是以C語言編寫的函式示例:
c
Copy code
#include <stdio.h>
// 函式原型
int search(int A[], int n, int x);
int main() {
int A[] = {1, 2, 3, 4, 5, 3, 2};
int n = sizeof(A) / sizeof(A[0]);
int x = 3;
// 呼叫 search 函式並打印結果
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);
}
return 0;
}
// 循序搜尋函式的實現
int search(int A[], int n, int x) {
int index = -1; // 用於記錄符合條件的最大索引
for (int i = 0; i < n; i++) {
if (A[i] == x) {
index = i; // 更新符合條件的索引
}
}
return index; // 返回最終結果,如果未找到則為 -1
}
在這個函式中,我們使用一個for循環來遍歷陣列A[]的所有元素。每當發現一個元素的值等於目標值x時,我們更新變量index的值為當前的索引i。由於循環是從陣列的開始到結束進行的,最後一次更新的index值將會是符合條件的最大索引,正好符合題目的要求。如果循環結束後index仍為初始值-1,則表示陣列中不存在目標值,函式最後返回index的值。