在C語言中,可以使用線性搜索、二分搜索、哈希表等方式實(shí)現(xiàn)數(shù)據(jù)的查找。
#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // 返回目標(biāo)值在數(shù)組中的索引
}
}
return -1; // 表示未找到目標(biāo)值
}
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("未找到目標(biāo)值\n");
} else {
printf("目標(biāo)值在數(shù)組中的索引為:%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; // 返回目標(biāo)值在數(shù)組中的索引
}
if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // 表示未找到目標(biāo)值
}
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("未找到目標(biāo)值\n");
} else {
printf("目標(biāo)值在數(shù)組中的索引為:%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; // 哈希表已滿,未找到目標(biāo)值
}
if (hashTable[index].key == key) {
*value = hashTable[index].value;
return true; // 找到目標(biāo)值
}
index = (index + 1) % SIZE;
count++;
}
return false; // 未找到目標(biāo)值
}
int main() {
insert(1, 10);
insert(2, 20);
insert(3, 30);
int target = 2;
int value;
if (search(target, &value)) {
printf("目標(biāo)值的鍵:%d,值:%d\n", target, value);
} else {
printf("未找到目標(biāo)值\n");
}
return 0;
}