Open-addressable structure hash table

#define NULLKEY -1
#define DELKEY -2
typedef int KeyType;
typedef struct {
	KeyType key;
	int count; // number of probes domain
}HashTable;

  

void InsertHT(HashTable HT[], KeyType k, int& n, int m, int p)
{
	// n number of elements in the hash table in total, m long table
	int i, adr;
	addr = k% p;
	if (HT[adr].key == NULLKEY || HT[adr].key == DELKEY)
	{
		HT[adr].key = k;
		HT[adr].count = 1;
	}
	else
	{
		i = 1;
		do {
			adr = (adr + 1)% m; // m is not p
			i++;
		} while (HT[adr].key != NULLKEY && HT[adr].key != DELKEY);
		HT[adr].key = k;
		HT[adr].count = i;
	}
	n++;
}

  

void CreateHT(HashTable HT[], KeyType keys[], int& n, int m, int p,int n1)
{
	// n1 is an array of keys length
	int i;
	for ( i = 0; i < m; i++)
	{
		HT[i].key = NULLKEY;
		HT[i].count = 0;
	}
	n = 0;
	for (i = 0; i < n1; i++)
		InsertHT(HT, keys[i], n, m, p);
}

  

bool DeletHT(HashTable HT[], KeyType k, int& n, int m, int p)
{
	int adr = k % p;
	while (HT[adr].key != NULLKEY && HT[adr].key != k)
		adr = (adr + 1)% m;
	if (HT[adr].key == k)
	{
		HT[adr].key = DELKEY;
		return true;
	}
	else
		return false;
}

  

void SerachHT(HashTable HT[], KeyType k, int& n, int m, int p)
{
	int i = 1;
	int adr = k % p;
	while (HT[adr].key != NULLKEY && HT[adr].key != k)
	{
		adr = (adr + 1)% m;
		i++;
	}
	if (HT[adr].key == k)
		printf ( "Success: Keyword% d,% d times comparing \ n", k, i);
	else
		printf ( "Failed: keyword% d,% d compare times \ n", k, i);
}

  

void ASL(HashTable HT[], int n, int m, int p)
{
	int i, j, s;
	int suc = 0,unsuc = 0;
	for (i = 0; i < m; i++)
	{
		if (HT[i].key != NULLKEY)
			suc += HT[i].count;
	}
	printf ( "ASL case of success =% g \ n", suc * 1.0 / n);
	for (i = 0; i < p; i++)
	{
		s = 1;
		j = i;
		while (HT[j].key != NULLKEY)
		{
			s++;
			j = (j + 1) % m;
		}
		unsuc += s;
	}
	printf ( "case of failure ASL =% g \ n", unsuc * 1.0 / p);
}

  Test: KeyType keys [] = {16,74,60,43,54,90,46,31,29,88,77}, int p = 13, m = 13, n = 0, n1 = 11;

Guess you like

Origin www.cnblogs.com/KIROsola/p/11986689.html