1. 程式人生 > >c++中的雜湊演算法實現

c++中的雜湊演算法實現

/*
	雜湊演算法的實現原理是:
		通過獲得你要排序的序列長度(m),
		然後得出比這個 m 大的素數作為陣列的長度(n),
		然後對接下來的輸入資料(D)進行取模運算(v=D%n),
		然後取模之後的資料存到陣列中。
		但是這樣做會出現當個取模之後餘數相同的情況 
		我這裡介紹常用的解決方法  拉鍊雜湊 : 
		拉鍊雜湊 就是先進行雜湊,但是在儲存的時候使用連結串列。
		這樣做的弊端是,當取模之後的餘數相同的情況特別嚴重的時候會容易出現最壞的情況
		這時候你可以做的就是更改 n 值或者採用其他的解決方案,但是推薦採取更改 n 值 
		 
*/
#include 
using namespace std;

typedef int Elm;
#define Mod  7;

struct nds
{
	Elm data;
	nds* next;
};
struct L
{
	int num;//標誌這個連結串列的元素個數 
	nds *first; 
};
L[Mod];
void haxi_create(Elm *p,int n)
{
	int k=0;Elm r;nds *s,*h;
	while(kdata=p[k];
		s->next=NULL;
		if(L[r]->first==NULL) L[r]->first=s;
		else 
		{
			h=L[r]->first;
			while(h->next) h=h->next;
			h->next=s;
		}
	}
}
int haxi_find(Elm e)
{
	Elm b=E%Mod;
	bool flage=false;	
	nds*o=L[b]->first;
	if(!o) return -1;
	while(o)
	{
		if(o->data==e) 
		{
			flage=true;
			break; 
		}
		o=o->next;
	}
	if(flage) return 1;
	else return -1;
}