直接寻址表
当关键字的全域U比较小时,直接寻址是一种简单而有效的技术。
另外,假设没有两个元素具有相同的关键字.
如图:
几个字典的操作实现比较简单:
DIRECT_ADDRESS_SEARCH(T, k)
return T[k]
DIRECT_ADDRESS_INSERT(T, x)
T[x.key] = x
DIRECT_ADDRESS_DELETE(T, x)
T[x.key] = NULL
对于有些应用,直接寻址本身就可以存放动态集合中的元素。也就是说,并不把每个元素的关键字及其卫星数据都放在直接寻址表外部的一个对象中,再由表中某个槽的指针指向该对象,而是直接把对象存放在表的槽中.
一个哈希表的实现:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define SIZE 20
struct DataItem{
int data;
int key;
};
struct DataItem *hashArray[SIZE];
struct DataItem *dummyItem;
struct DataItem *item;
int hashCode(int key)
{
return key % SIZE;
}
struct DataItem *search(int key)
{
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}
void insert(int key, int data)
{
struct DataItem *item = (struct DataItem*)malloc(sizeof(struct DataItem));
item->data = data;
item->key = key;
int hashIndex = hashCode(key);
while (hashArray[hashIndex]!= NULL && hashArray[hashIndex]->key != -1)
{
++hashIndex;
hashIndex %= SIZE;
}
hashArray[hashIndex] = item;
}
struct DataItem *delete(struct DataItem *item)
{
int key = item->key;
int hashIndex = hashCode(key);
while (hashArray[hashIndex] != NULL)
{
if (hashArray[hashIndex]->key == key)
{
struct DataItem *temp = hashArray[hashIndex];
//assign a dummy item at deleted position
hashArray[hashIndex] = dummyItem;
return temp;
}
++hashIndex;
hashIndex %= SIZE;
}
return NULL;
}
void display()
{
int i = 0;
for (i=0; i<SIZE; ++i)
{
if (hashArray[i] != NULL)
printf("(%d,%d)", hashArray[i]->key, hashArray[i]->data);
else
printf("~~");
}
printf("\n");
}
int main()
{
dummyItem = (struct DataItem*)malloc(sizeof(struct DataItem));
dummyItem->data = -1;
dummyItem->key = -1;
insert(1, 20);
insert(2, 70);
insert(42, 80);
insert(4, 25);
insert(12, 44);
insert(14, 32);
insert(17, 11);
insert(13, 78);
insert(37, 97);
display();
item = search(37);
if (item != NULL)
printf("Element found:%d\n", item->data);
else
printf("Element not found\n");
delete(item);
item = search(37);
if (item != NULL)
printf("Element found:%d\n", item->data);
else
printf("Element not found\n");
return 0;
}
参考:
https://www.tutorialspoint.com/data_structures_algorithms/hash_table_program_in_c.htm