开放地址——平法探测散列表

对于开放地址的散列,要找出一些办法使得冲突的尽可能降低.
平法探测法是指当冲突时若地址为k,则下一个探测的地址为k+i^2(i=1,2,3,4…)。
(1)初始化,

#include "stdafx.h"
#include "stdlib.h"
#include "malloc.h"
#include"math.h"
#include "time.h"
#define Num 100
#define deleted -1
#define Empty 0
#define full 1
typedef struct HashEntry Cell;
typedef struct Hashtbl * Hashtable;
struct HashEntry
{
    int Info;
    int Element;
};
struct Hashtbl
{
    int TableSize;
    Cell *TheCells; 
};
Hashtable Initialize(int TableSize)
{
    //开放地址法
    Hashtable H;
    H = (Hashtable)malloc(sizeof(Hashtbl));
    H->TableSize = NextPrime(TableSize);
    H->TheCells = (Cell*)malloc(sizeof(Cell)*H->TableSize);
    for(int i = 0;i<=H->TableSize-1;i++)
        H->TheCells[i].Info = Empty;
    return H;
}
int Hash(int key,int TableSize)
{
    return key%TableSize;
}
int Find(Hashtable H,int x )
{
    int CollisionNum = 0;
    int Index = Hash(x,H->TableSize);
    while(H->TheCells[Index].Info!=Empty&&H->TheCells[Index].Element!=x)
    {
        if(CollisionNum == H->TableSize)
        {
            puts("error:the Table is full");
            return 0;
        }
        Index += 2*(++CollisionNum) - 1;
        if(Index >=H->TableSize)
            Index = Index % H->TableSize;
    }
    return Index;
}

(2)插入

void Insert(Hashtable H,int x)
{
    int index = Find(H,x);
    if(H->TheCells[index].Info!=full)//如果x的位置可以插入
    {
            H->TheCells[index].Element = x;//将空位置加入元素
            H->TheCells[index].Info = full;//将信息改变
    }
}

你可能感兴趣的:(开放地址——平法探测散列表)