在C语言中,可以使用线性搜索、二分搜索、哈希表等方式实现数据的查找。
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // 返回目标值在数组中的索引
}
}
return -1; // 表示未找到目标值
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int result = linearSearch(arr, n, target);
if (result == -1) {
printf("未找到目标值\n");
} else {
printf("目标值在数组中的索引为:%d\n", result);
}
return 0;
}
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target) {
return mid; // 返回目标值在数组中的索引
}
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // 表示未找到目标值
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 3;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1) {
printf("未找到目标值\n");
} else {
printf("目标值在数组中的索引为:%d\n", result);
}
return 0;
}
#include <stdio.h>
#include <stdbool.h>
#define SIZE 10
typedef struct {
int key;
int value;
} Entry;
Entry hashTable[SIZE];
int hashCode(int key) {
return key % SIZE;
}
void insert(int key, int value) {
int index = hashCode(key);
while (hashTable[index].key != 0) {
index = (index + 1) % SIZE;
}
hashTable[index].key = key;
hashTable[index].value = value;
}
bool search(int key, int* value) {
int index = hashCode(key);
int count = 0;
while (hashTable[index].key != 0) {
if (count > SIZE) {
return false; // 哈希表已满,未找到目标值
}
if (hashTable[index].key == key) {
*value = hashTable[index].value;
return true; // 找到目标值
}
index = (index + 1) % SIZE;
count++;
}
return false; // 未找到目标值
}
int main() {
insert(1, 10);
insert(2, 20);
insert(3, 30);
int target = 2;
int value;
if (search(target, &value)) {
printf("目标值的键:%d,值:%d\n", target, value);
} else {
printf("未找到目标值\n");
}
return 0;
}