查找算法:
二分查找:O(lg N) ,单调性
(顺序表中查找)用数组下标索引来查找 O(1)
arr[ ] 下标int ————> 任意类型数据 (映射)
哈希表 任意类型数据 ————> 任意类型数据 (映射)
哈希表是为了追求查找算法时间复杂度为O(1),仿用数组下标索引来查找设计
哈希函数的作用:将任意类型的数据,映射成int,作为下标来存储数据
哈希表:
1. 需要一片连续的存储空间(顺序表、数组)
2. size 空间大小
3. 哈希函数
冲突处理方法:
1. 开放定值法;往后一个空间探测是否存值了,会产生堆聚现象;二次探测 1^2, 2^2, 3^2,…
2. 拉链法; 建立一个链表, 来存储冲突元素
3. 再哈希(散列)法
4. 建立公共溢出区
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *str;
struct Node *next;
} Node;
typedef struct HashTable {
Node **data;
int size;
} HashTable;
Node *init_node(char *str, Node *head) {
Node *p = (Node *)malloc(sizeof(Node));
p->str = strdup(str);
p->next = head;
return p;
}
HashTable *init_hashtable(int n) {
HashTable *h = (HashTable *)malloc(sizeof(HashTable));
h->size = n << 1;
h->data = (Node **)calloc(h->size, sizeof(Node *));
return h;
}
int BKDRHash(char *str) {
int seed = 31, hash = 0;
for (int i = 0; str[i]; i++) hash = hash * seed + str[i];
return hash & 0x7fffffff;
}
int insert(HashTable *h, char *str) {
int hash = BKDRHash(str);
int ind = hash % h->size;
h->data[ind] = init_node(str, h->data[ind]);
return 1;
}
int search(HashTable *h, char *str) {
int hash = BKDRHash(str);
int ind = hash % h->size;
Node *p = h->data[ind];
while (p && strcmp(p->str, str)) p = p->next;
return p != NULL;
}
void clear_node(Node *node) {
if (node == NULL) return ;
Node *p = node, *q;
while (p) {
q = p->next;
free(p->str);
free(p);
p = q;
}
return ;
}
void clear(HashTable *h) {
if (h == NULL) return ;
for (int i = 0; i < h->size; i++) clear_node(h->data[i]);
free(h->data);
free(h);
return ;
}
int main() {
int op;
#define MAX_N 100
char str[MAX_N + 5] = {0};
HashTable *h = init_hashtable(MAX_N + 5);
while (~scanf("%d%s", &op, str)) {
switch (op) {
case 0:
printf("insert %s from HashTable\n", str);
insert(h, str);
break;
case 1:
printf("search %s from HashTabe result = %d\n", str, search(h, str));
break;
}
}
#undef MAX_N
clear(h);
return 0;
}
> 0 hello
insert hgr from HashTable
> 0 hall
insert ty from HashTable
> 0 hsalome
insert htq from HashTable
> 1 hello
search hgr from HashTabe result = 1
> 1 helll
search yu from HashTabe result = 0
> 1 hsalome
search ty from HashTabe result = 1
^C