【数据结构脑图系列06】散列查找

脑图

在这里插入图片描述

代码

//Hashing.cpp
#include<iostream>
#include<cmath>
#include<stdlib.h>
#define MAXTABLESIZE 100000
#define NOTFIND -1

typedef int ElementType;
typedef enum{     
	Legitimate,Empty
} EntryType;   

typedef struct HashEntry Cell;
struct HashEntry{    
	ElementType data;  // 值
	EntryType info;   // 状态 
};

typedef struct HashTbl *HashTable;
struct HashTbl{  // 哈希表
	int TableSize;  // 大小 
	Cell *Cells;   // 数组 
};

using namespace std;

// 除留余数法哈希函数 
int Hash(int key,int p){
	return key%p;
}

// 查找下一个素数 
int NextPrime(int N){
	int p = N%2?N:N+1;
	int i;
	if(N<=2)
		return 2;
	else if(N<=3)
		return 3; 
	while(p <= MAXTABLESIZE){
		for(i=(int)sqrt(p);i>2;i--)
			if(!(p%i))   // 不是素数 
				break;
		if(i==2)  // 找到了
			break;
		p += 2; 
	}
	return p;
}

// 创建哈希表 
HashTable CreateTable(int TableSize){
	HashTable H;
	H = (HashTable)malloc(sizeof(struct HashTbl));
	H->TableSize = NextPrime(TableSize);
	H->Cells = (Cell *)malloc(sizeof(struct HashEntry)*H->TableSize);
	for(int i=0;i<H->TableSize;i++)
		H->Cells[i].info = Empty;
	return H;	
}

//查找哈希表 
int Find(HashTable H,ElementType key){
	int NewPos,CurrentPos;
	int CNum = 0;  // 记录冲突次数 
	CurrentPos = NewPos = Hash(key,H->TableSize);
	// 如果当前状态不为空,且一直不等,一直做 
	while(H->Cells[NewPos].info != Empty && H->Cells[NewPos].data != key){
		CNum++;
		NewPos = (CurrentPos + CNum*CNum)%H->TableSize;
		if(CNum == H->TableSize/2) // 没找到
			return NOTFIND;
	}
	return NewPos;
}

//插入
int Insert(HashTable H,ElementType key){
	int pos;
	pos = Find(H,key);
	if(pos==NOTFIND) // 如果没找到 
		return NOTFIND;
	else if(H->Cells[pos].info != Legitimate){
		H->Cells[pos].info = Legitimate;
		H->Cells[pos].data = key;
	}
	return pos;
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值