How to implement the sequential search algorithm in the C language?
Here is an example code implementing a sequential search algorithm in C language.
#include <stdio.h>
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // 返回找到的元素的索引
}
}
return -1; // 返回-1表示未找到
}
int main() {
int arr[] = {3, 5, 2, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 4;
int index = sequentialSearch(arr, n, key);
if (index != -1) {
printf("元素 %d 在数组中的索引为 %d\n", key, index);
} else {
printf("元素 %d 未找到\n", key);
}
return 0;
}
This program first defines a sequentialSearch function that takes an array, array size, and search key as parameters. It uses a for loop to iterate through each element in the array, and if a match is found with the key, it returns the index of that element. If no matching element is found after the loop ends, it returns -1 to indicate not found.
In the main function, we defined an array named arr with some integers, determined the size of the array n, and identified the key to be searched. We then called the sequentialSearch function to find the index of the key in the array, and printed a message corresponding to the returned index.
When executing the program, it will output the index of element 4 in the array as 3, indicating that the keyword 4 is found at index 3 in the array. If the keyword being searched for is not in the array, it will output that element 4 is not found.