用c语言写出最快的查找方法
时间: 2024-02-28 20:52:10 浏览: 25
在C语言中,最快的查找方法是使用哈希表。哈希表是一种基于键值对的数据结构,它通过将键值映射到一个固定大小的数组中来进行快速查找。
以下是一个简单的哈希表实例,可以用来存储字符串和对应的整数值:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1000
typedef struct {
char *key;
int value;
} hash_item;
typedef struct {
hash_item **items;
} hash_table;
hash_table *create_hash_table() {
hash_table *table = malloc(sizeof(hash_table));
table->items = calloc(TABLE_SIZE, sizeof(hash_item*));
return table;
}
void free_hash_table(hash_table *table) {
for (int i = 0; i < TABLE_SIZE; i++) {
hash_item *item = table->items[i];
if (item != NULL) {
free(item->key);
free(item);
}
}
free(table->items);
free(table);
}
int hash_function(char *key) {
int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash += key[i];
}
return hash % TABLE_SIZE;
}
void hash_set(hash_table *table, char *key, int value) {
int index = hash_function(key);
hash_item *item = malloc(sizeof(hash_item));
item->key = strdup(key);
item->value = value;
table->items[index] = item;
}
int hash_get(hash_table *table, char *key) {
int index = hash_function(key);
hash_item *item = table->items[index];
if (item == NULL) {
return -1;
}
return item->value;
}
int main() {
hash_table *table = create_hash_table();
hash_set(table, "apple", 1);
hash_set(table, "banana", 2);
hash_set(table, "cherry", 3);
printf("%d\n", hash_get(table, "apple"));
printf("%d\n", hash_get(table, "banana"));
printf("%d\n", hash_get(table, "cherry"));
free_hash_table(table);
return 0;
}
```
在这个例子中,我们使用了一个简单的哈希函数将字符串键映射为哈希表中的索引。然后,我们使用 `hash_set()` 函数将键值对插入哈希表中;使用 `hash_get()` 函数查找键对应的值。
哈希表的平均时间复杂度为O(1),可以实现非常快速的查找。