散列表(平方探测法解决冲突)

17 篇文章 0 订阅
12 篇文章 0 订阅

用平方探测法来解决冲突的实现

头文件:

#ifndef HASHQUAD_H_INCLUDED
#define HASHQUAD_H_INCLUDED

typedef unsigned int Index;
typedef Index Position;

typedef int ElementType;

struct HashTbl;
typedef struct HashTbl *HashTable;

HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P,HashTable H);
HashTable ReHash(HashTable H);

#endif // HASHQUAD_H_INCLUDED

实现:

#include <stdio.h>
#include <stdlib.h>
#include "HashQuad.h"
#include <limits.h>
#include <math.h>

#define MinTableSize 100

enum KindOfEntry {Legitimate,Empty,Deleted};

struct HashEntry
{
    ElementType Element;
    enum KindOfEntry Info;
};

typedef struct HashEntry Cell;

struct HashTbl
{
    int TableSize;
    Cell *TheCells;
};

void Error(char *s)
{

}

void FatalError(char *s)
{

}

int IsPrime(int num)
{
    if(num == 1) return 0;
    int i;
    for(i = 2; i <= sqrt(num); i++)
        if(num%i == 0)
            return 0;
    return 1;
}
int NextPrime(int TableSize)
{
    int i;
    for(i = TableSize; i < INT_MAX; i++)
        if(IsPrime(i))
            return i;
    return 0;
}

/* Boss 散列函数 Function of Hash */
Position Hash(const ElementType Key,int TableSize)
{
    return Key%TableSize;
}

HashTable InitializeTable(int TableSize)
{
    HashTable H;
    int i;

    if(TableSize < MinTableSize)
    {
        Error("Table size too small");
        return NULL;
    }

    H = malloc(sizeof(struct HashTbl));
    if(H == NULL)
        FatalError("Out of space!!!");

    H->TableSize = NextPrime(TableSize);

    H->TheCells = malloc(sizeof(Cell)*H->TableSize);
    if(H->TheCells == NULL)
        FatalError("Out of space!!!");

    for(i = 0; i < H->TableSize; i++)
        H->TheCells[i].Info = Empty;

    return H;
}

Position Find(ElementType Key,HashTable H)
{
    Position CurrentPos;
    int CollisionNum;

    CollisionNum = 0;
    CurrentPos = Hash(Key,H->TableSize);

    while(H->TheCells[ CurrentPos ].Info != Empty &&
            H->TheCells[ CurrentPos ].Element != Key)
    {
        CurrentPos += ++CollisionNum << 1 - 1;
        if(CurrentPos >= H->TableSize)
            CurrentPos -= H->TableSize;
    }
    return CurrentPos;
}

void Insert(ElementType Key,HashTable H)
{
    Position Pos;

    Pos = Find(Key,H);
    if( H->TheCells[ Pos ].Info != Legitimate )
    {
        H->TheCells[ Pos ].Info = Legitimate;
        H->TheCells[ Pos ].Element = Key;
    }
}

int main()
{
    HashTable H = InitializeTable(1000);
    Insert(10000,H);
    Position P = Find(10000,H);
    printf("%d\n",P);
    return 0;
}

注:代码摘自《数据结构与算法分析第二版》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值