MOOC 数据结构 11-散列2 Hashing

题目

The task of this problem is simple: insert a sequence of distinct positive integers into a hash table, and output the positions of the input numbers. The hash function is defined to be H(key)=key%TSize where TSize is the maximum size of the hash table. Quadratic probing (with positive increments only) is used to solve the collisions.

Note that the table size is better to be prime. If the maximum size given by the user is not prime, you must re-define the table size to be the smallest prime number which is larger than the size given by the user.

Input Specification:
Each input file contains one test case. For each case, the first line contains two positive numbers: MSize (≤10^4) and N (≤MSize) which are the user-defined table size and the number of input numbers, respectively. Then N distinct positive integers are given in the next line. All the numbers in a line are separated by a space.

Output Specification:
For each test case, print the corresponding positions (index starts from 0) of the input numbers in one line. All the numbers in a line are separated by a space, and there must be no extra space at the end of the line. In case it is impossible to insert the number, print “-” instead.

Sample Input:

4 4
10 6 4 15

Sample Output:

0 1 4 -

思路和小结

这是一道散列表的基础练习题,考察散列表基础操作集、除留余数法和平方探测,题目不难,但是也有几处需要注意的地方
在这里插入图片描述

注意点

1.老师给出的代码中 散列表的大小TableSize 直接取元素个数的下一个素数,即

H->TableSize = NextPrime(TableSize);
int NextPrime( int N )
{ /* 返回大于N且不超过MAXTABLESIZE的最小素数 */
   	int i, p = (N%2)? N+2 : N+1; /*从大于N的下一个奇数开始 */

   	while( p <= MAXTABLESIZE ) {
       	for( i=(int)sqrt(p); i>2; i-- )
          		if ( !(p%i) ) break; /* p不是素数 */
       	if ( i==2 ) break; /* for正常结束,说明p是素数 */
       	else  p += 2; /* 否则试探下一个奇数 */
   	}
   	return p;
}

而这里是说,如果元素个数MSize 不是素数,再就取下一个素数

int NextPrime( int M )
{
	while(!isPrime( M )){
		M++;
	}
	
	return M;
}

bool isPrime( int M )
{
	if(M == 1) return false;
	
	int i;
	for(i=2;i<=(int)sqrt(M);i++){
		if(M%i == 0){
			return false;
		}
	}
	
	return true;
}

2.对于最小的MSize == 1,下一个素数是2,需要单独说明,否则会有测试点卡住

3.由于本题只是涉及插入和查找,并没有删除,而且所有的数据都是正整数,所以表的状态栏Info可以去掉,直接初始化表为Empty
即结构

typedef enum { Legitimate, Empty, Deleted } EntryType;

typedef struct HashEntry Cell; /* 散列表单元类型 */
struct HashEntry{
    	ElementType Data; /* 存放元素 */
    	EntryType Info;   /* 单元状态 */
};

可以去掉

5.个人感觉是最难的点:怎么判断新元素插入失败
我们先来看线性探测:Di = 0,1,2,3,…,TableSize-1 当探测增量Di = TableSize-1 时,还没有探测到适合的位置,那就说明插入失败。
再来看平方探测:Di^2 Di = 0,1,2,3,… 很明显 当Di探测到TableSize-1时 还没有探测到合适的位置,那就是插入失败;实际上,其实只要探测到 Di = TableSize/2 时 就能判断是否有合适的位置,代码也通过了;可是具体严密的数学证明 我给不了,保险就探测到Di < TableSize吧

这是老师写的

Position Find( HashTable H, ElementType Key )
{
  	Position CurrentPos, NewPos;
  	int CNum = 0; /* 记录冲突次数 */

  	NewPos = CurrentPos = Hash( Key, H->TableSize ); /* 初始散列位置 */
  	/* 当该位置的单元非空,并且不是要找的元素时,发生冲突 */
  	while( H->Cells[NewPos].Info!=Empty && H->Cells[NewPos].Data!=Key ) {
                                         /* 字符串类型的关键词需要 strcmp 函数!! */
      	/* 统计1次冲突,并判断奇偶次 */
      	if( ++CNum%2 ){ /* 奇数次冲突 */
          	NewPos = CurrentPos + (CNum+1)*(CNum+1)/4; /* 增量为+[(CNum+1)/2]^2 */
          	if ( NewPos >= H->TableSize )
              	NewPos = NewPos % H->TableSize; /* 调整为合法地址 */
      	}
      	else { /* 偶数次冲突 */
          	NewPos = CurrentPos - CNum*CNum/4; /* 增量为-(CNum/2)^2 */
          	while( NewPos < 0 )
              	NewPos += H->TableSize; /* 调整为合法地址 */
      	}
  	}
  	return NewPos; /* 此时NewPos或者是Key的位置,或者是一个空单元的位置(表示找不到)*/
}

这是我按自己的理解写的

Position Find( HashTable* H,ElementType Key )
{
	Position NewPos,CurrentPos;
	CurrentPos = Hash( Key,H->TableSize);
	
	int Di; //探测增量
	for(Di=0;Di<H->TableSize/2;Di++){
		
		NewPos = (CurrentPos + Di*Di) % H->TableSize;
		if(H->Cells[NewPos].Info == Empty || H->Cells[NewPos].Data == Key){
			break;
		}
		
		NewPos = (CurrentPos - Di*Di + H->TablseSize)%H->TablseSize;
		if(H->Cells[NewPos].Info == Empty || H->Cells[NewPos].Data == Key){
          	break;
		}
	}
	
	return NewPos;
}

完整代码如下

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <math.h>
#define NotFound -1
#define Empty 0

typedef int Index;
typedef Index Position;

typedef struct _HashTable{
	int TableSize;
	int* Cells;
}HashTable;

HashTable* CreateHashTable();

int NextPrime( int M );

bool isPrime( int M );

void BuildHashTable( HashTable* H );

void Insert( HashTable* H,int key,Position* ptrPos );

Position Find( HashTable* H,int Key );

Position Hash(int Key,int TableSize );

void Print( Position pos[],int N );

int main()
{
	HashTable* H = CreateHashTable();
	
	BuildHashTable( H );
	
	return 0;
}

HashTable* CreateHashTable()
{
	int M;
	scanf("%d",&M);
	
	HashTable* H = (HashTable*)malloc(sizeof(HashTable));
	
	H->TableSize = NextPrime( M );
	H->Cells = malloc(sizeof(int)*H->TableSize);
	
	int i;
	for(i=0;i<H->TableSize;i++){
		
		H->Cells[i] = Empty;
	}
	
	return H;
}

int NextPrime( int M )
{
	while(!isPrime( M )){
		M++;
	}
	
	return M;
}

bool isPrime( int M )
{
	if(M == 1) return false;
	
	int i;
	for(i=2;i<=(int)sqrt(M);i++){
		if(M%i == 0){
			return false;
		}
	}
	
	return true;
}

void BuildHashTable( HashTable* H )
{
	int i,N,Key;
	scanf("%d",&N);
	
	Position Pos[N];
	for(i=0;i<N;i++){
		
		scanf("%d",&Key);
		
		Insert( H,Key,&Pos[i] );
	}
	
	Print( Pos,N );
}

void Insert( HashTable* H,int Key,Position* ptrPos )
{
	Position Pos = Find( H,Key );
	
	if(H->Cells[Pos] == Empty){
		
		H->Cells[Pos] = Key;
		*ptrPos = Pos;
		
	}else{
		
		*ptrPos = NotFound;
	}
}

Position Find( HashTable* H,int Key )
{
	Position NewPos,CurrentPos;
	CurrentPos = Hash( Key,H->TableSize);
	
	int Di;
	for(Di=0;Di<H->TableSize/2;Di++){
		
		NewPos = (CurrentPos + Di*Di) % H->TableSize;
		if(H->Cells[NewPos] == Empty || H->Cells[NewPos] == Key){
			break;
		}
	}
	
	return NewPos;
}

Position Hash(int Key,int TableSize )
{
	return Key%TableSize;
}

void Print( Position Pos[],int N )
{
	int i;
	for(i=0;i<N;i++){
		
		if(i != 0){
			printf(" ");
		}
		
		if(Pos[i] != NotFound){
			printf("%d",Pos[i]);
		}else{
			printf("-");
		}	
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值