散列 - C语言实现(摘自数据结构与算法分析 C语言描述)

一、概述

  散列表(hash table)ADT只支持二叉查找树所允许的一部分操作,散列表的实现常常叫做散列(hashing)。散列是一种以常数平均时间执行插入、删除和查找的技术。但是,那些需要元素间任何排序信息的操作将不会得到有效的支持。

二、实现

  理想的散列表数据结构只不过是一个包含有关关键字的具有固定大小的数组。典型情况下,一个关键字就是一个带有相关值的字符串。我们把表的大小记作TableSize,并将其理解为散列数据结构的一部分而不仅仅是浮动于全局的某个变量。通常的习惯是让表从0到TableSize - 1变化。每个关键字被映射到从0到TableSize - 1这个范围中的某个数,并且被放到适当的单元中。这个映射就叫做散列函数(hash function),理想情况下它应该运算简单并且应该保证任何两个不同的关键字映射到不同的单元。不过,这是不可能的,因为单元的数目是有限的,而关键字实际上是用不完的。因此,我们寻找一个散列函数,该函数要在单元之间均匀地分配关键字。

  这就是散列的基本想法。剩下的问题则是要选择一个函数,决定当两个关键字散列到同一个值的时候(称为冲突(collision))应该做什么以及如何确定散列表的大小。

如果输入的关键字是整数,则一般合理的方法就是直接返回“Key mod Tablesize”的结果,除非Key碰巧具有某些不理想的性质。在这种情况下,散列函数的选择需要仔细考虑。

  解决冲突的方法有几种,我们将讨论其中最简单的两种:分离链接法和开放定址法。

1. 分离链接法

  其做法是将散列到同一个值的所有元素保留到一个表中,为方便起见,这些表都有表头(表的大小不是素数,用在这里是为了简单),如图1所示。


图1 分离链接散列表

文件名:hashsep.h

  1. #ifndef _HashSep_H   
  2.   
  3. typedef int ElementType;  
  4.   
  5. typedef unsigned int Index;  
  6.   
  7. struct ListNode;  
  8. typedef struct ListNode *Position;  
  9. struct HashTbl;  
  10. typedef struct HashTbl *HashTable;  
  11.   
  12. Index Hash( const int Key, int TableSize );  
  13.   
  14. HashTable InitializeTable( int TableSize );  
  15. void DestroyTable( HashTable H );  
  16. Position Find( ElementType Key, HashTable H );  
  17. void Insert( ElementType Key, HashTable H );  
  18. ElementType Retrieve( Position P );  
  19. /* Routines such as Delete and MakeEmpty are omitted */  
  20.   
  21.   
  22. #endif /* _HashSep_H */  
#ifndef _HashSep_H

typedef int ElementType;

typedef unsigned int Index;

struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;

Index Hash( const int Key, int TableSize );

HashTable InitializeTable( int TableSize );
void DestroyTable( HashTable H );
Position Find( ElementType Key, HashTable H );
void Insert( ElementType Key, HashTable H );
ElementType Retrieve( Position P );
/* Routines such as Delete and MakeEmpty are omitted */


#endif /* _HashSep_H */

文件名:hashsep.c

  1. #include "fatal.h"   
  2. #include "hashsep.h"   
  3. #define MinTableSize (10)   
  4. typedef Position List;  
  5.   
  6. Index Hash( const int Key, int TableSize )  
  7. {  
  8.     return Key % TableSize;  
  9. }  
  10.   
  11. struct ListNode  
  12. {  
  13.     ElementType Element;  
  14.     Position Next;  
  15. };  
  16.   
  17. /* List *TheList will be an array of lists,allocated later */  
  18. /* The lists use headers (for simplicity), */  
  19. /* though this wastes space */  
  20. struct HashTbl  
  21. {  
  22.     int TableSize;  
  23.     List *TheLists;  
  24. };  
  25.   
  26. /* Return next prime; assume N >= 10 */  
  27. static int  
  28. NextPrime( int N )  
  29. {  
  30.     int i;  
  31.   
  32.     if( N % 2 == 0 )  
  33.         N++;  
  34.     for( ; ; N += 2 )  
  35.     {  
  36.         for( i = 3; i * i <= N; i += 2 )  
  37.             if( N % i == 0 )  
  38.                 goto ContOuter;  /* Sorry about this! */  
  39.         return N;  
  40. ContOuter: ;  
  41.     }  
  42. }  
  43.   
  44. HashTable  
  45. InitializeTable( int TableSize )  
  46. {  
  47.     HashTable H;  
  48.     int i;  
  49.   
  50.     if ( TableSize < MinTableSize )  
  51.     {  
  52.         Error( "Table size too small" );  
  53.         return NULL;  
  54.     }  
  55.   
  56.     /* Allocate table */  
  57.     H = malloc( sizeofstruct HashTbl ) );  
  58.     if ( H == NULL)  
  59.         FatalError( "Out of space!!!" );  
  60.   
  61.     H->TableSize = NextPrime( TableSize );  
  62.   
  63.     /* Allocate array of lists */  
  64.     H->TheLists = malloc( sizeof( List ) * H->TableSize );  
  65.     if( H->TheLists == NULL )  
  66.         FatalError( "Out of space!!!" );  
  67.   
  68.     /* Allocate list headers */  
  69.     for( i = 0; i < H->TableSize; i++ )  
  70.     {  
  71.         H->TheLists[ i ] = malloc( sizeofstruct ListNode ) );  
  72.         if ( H->TheLists[ i ] == NULL )  
  73.             FatalError( "Out of space!!!" );  
  74.         else  
  75.             H->TheLists[ i ]->Next = NULL;  
  76.     }  
  77.       
  78.     return H;  
  79. }  
  80.   
  81. Position   
  82. Find( ElementType Key, HashTable H )  
  83. {  
  84.     Position P;  
  85.     List L;  
  86.   
  87.     L = H->TheLists[ Hash( Key, H->TableSize )];  
  88.     P = L->Next;  
  89.   
  90.     while( P != NULL && P->Element != Key )  
  91.         /* Probably need strcmp!! */  
  92.         P = P->Next;  
  93.       
  94.     return P;  
  95. }  
  96.   
  97. void  
  98. Insert( ElementType Key, HashTable H )  
  99. {  
  100.     Position Pos, NewCell;  
  101.     List L;  
  102.       
  103.     Pos = Find( Key, H );  
  104.     if ( Pos == NULL ) /* Key is not found */  
  105.     {  
  106.         NewCell = malloc( sizeofstruct ListNode ) );  
  107.         if ( NewCell == NULL )  
  108.             FatalError( "Out of space!!!" );  
  109.         else  
  110.         {  
  111.             L = H->TheLists[ Hash( Key, H->TableSize ) ];  
  112.             NewCell->Next = L->Next;  
  113.             NewCell->Element = Key; /* Probably need strcpy!! */  
  114.             L->Next = NewCell;  
  115.         }  
  116.     }  
  117. }  
  118. void  
  119. DestroyTable( HashTable H )  
  120. {  
  121.     int i;  
  122.   
  123.     for( i = 0; i < H->TableSize; i++ )  
  124.     {  
  125.         Position P = H->TheLists[ i ];  
  126.         Position Tmp;  
  127.   
  128.         while( P != NULL )  
  129.         {  
  130.             Tmp = P->Next;  
  131.             free( P );  
  132.             P = Tmp;  
  133.         }  
  134.     }  
  135.   
  136.     free( H->TheLists );  
  137.     free( H );  
  138. }  
  139.   
  140.   
  141. ElementType Retrieve( Position P )  
  142. {  
  143.     return P->Element;  
  144. }  
#include "fatal.h"
#include "hashsep.h"
#define MinTableSize (10)
typedef Position List;

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

struct ListNode
{
	ElementType Element;
	Position Next;
};

/* List *TheList will be an array of lists,allocated later */
/* The lists use headers (for simplicity), */
/* though this wastes space */
struct HashTbl
{
	int TableSize;
	List *TheLists;
};

/* Return next prime; assume N >= 10 */
static int
NextPrime( int N )
{
	int i;

	if( N % 2 == 0 )
		N++;
	for( ; ; N += 2 )
	{
		for( i = 3; i * i <= N; i += 2 )
			if( N % i == 0 )
				goto ContOuter;  /* Sorry about this! */
		return N;
ContOuter: ;
	}
}

HashTable
InitializeTable( int TableSize )
{
	HashTable H;
	int i;

	if ( TableSize < MinTableSize )
	{
		Error( "Table size too small" );
		return NULL;
	}

	/* Allocate table */
	H = malloc( sizeof( struct HashTbl ) );
	if ( H == NULL)
		FatalError( "Out of space!!!" );

	H->TableSize = NextPrime( TableSize );

	/* Allocate array of lists */
	H->TheLists = malloc( sizeof( List ) * H->TableSize );
	if( H->TheLists == NULL )
		FatalError( "Out of space!!!" );

	/* Allocate list headers */
	for( i = 0; i < H->TableSize; i++ )
	{
		H->TheLists[ i ] = malloc( sizeof( struct ListNode ) );
		if ( H->TheLists[ i ] == NULL )
			FatalError( "Out of space!!!" );
		else
			H->TheLists[ i ]->Next = NULL;
	}
	
	return H;
}

Position 
Find( ElementType Key, HashTable H )
{
	Position P;
	List L;

	L = H->TheLists[ Hash( Key, H->TableSize )];
	P = L->Next;

	while( P != NULL && P->Element != Key )
		/* Probably need strcmp!! */
		P = P->Next;
	
	return P;
}

void
Insert( ElementType Key, HashTable H )
{
	Position Pos, NewCell;
	List L;
	
	Pos = Find( Key, H );
	if ( Pos == NULL ) /* Key is not found */
	{
		NewCell = malloc( sizeof( struct ListNode ) );
		if ( NewCell == NULL )
			FatalError( "Out of space!!!" );
		else
		{
			L = H->TheLists[ Hash( Key, H->TableSize ) ];
			NewCell->Next = L->Next;
			NewCell->Element = Key; /* Probably need strcpy!! */
			L->Next = NewCell;
		}
	}
}
void
DestroyTable( HashTable H )
{
	int i;

	for( i = 0; i < H->TableSize; i++ )
	{
		Position P = H->TheLists[ i ];
		Position Tmp;

		while( P != NULL )
		{
			Tmp = P->Next;
			free( P );
			P = Tmp;
		}
	}

	free( H->TheLists );
	free( H );
}


ElementType Retrieve( Position P )
{
	return P->Element;
}

文件名:main.c

  1. #include "hashsep.h"   
  2. #include <stdio.h>   
  3.   
  4. int main()  
  5. {  
  6.     HashTable H = InitializeTable( 10 );  
  7.     int i;  
  8.     printf( "HashTable:\n" );  
  9.     for ( i = 1; i < 11; i++ )  
  10.     {  
  11.         Insert( i * i, H );  
  12.         printf( "%d:%d\n", i*i, Hash( i * i, 10 ) );  
  13.     }  
  14.     return 0;  
  15. }  
#include "hashsep.h"
#include <stdio.h>

int main()
{
	HashTable H = InitializeTable( 10 );
	int i;
	printf( "HashTable:\n" );
	for ( i = 1; i < 11; i++ )
	{
		Insert( i * i, H );
		printf( "%d:%d\n", i*i, Hash( i * i, 10 ) );
	}
	return 0;
}



2. 开放定址法

分离链接散列算法的缺点是需要指针,由于给新单元分配地址需要时间,因此就导致算法的速度多少有些减慢,同时算法实际上还要求对另一种数据结构的实现。除使用链表解决冲突外,开放定址散列法(Open addressing hashing)是另外一种不用链表解决冲突的方法。在开放定址散列算法系统中,如果有冲突发生,那么就要尝试选择另外的单元,直到找出空的单元为止。

文件名:hashquad.h

  1. #ifndef _HashQuad_H   
  2.   
  3. typedef int ElementType;  
  4.   
  5. typedef unsigned int Index;  
  6. typedef Index Position;  
  7.   
  8. struct HashTbl;  
  9. typedef struct HashTbl *HashTable;  
  10.   
  11. static int NextPrime( int N );  
  12. Index Hash( ElementType Key, int TableSize );  
  13. HashTable InitializeTable( int TableSize );  
  14. void DestroyTable( HashTable H );  
  15. Position Find( ElementType Key, HashTable H );  
  16. void Insert( ElementType Key, HashTable H );  
  17. ElementType Retrieve( Position P, HashTable H );  
  18. HashTable Rehash( HashTable H );  
  19. /* Routines such as Delete and MakeEmpty are omitted */  
  20. #endif /* _HashQuad_H */  
#ifndef _HashQuad_H

typedef int ElementType;

typedef unsigned int Index;
typedef Index Position;

struct HashTbl;
typedef struct HashTbl *HashTable;

static int NextPrime( int N );
Index Hash( ElementType Key, int TableSize );
HashTable InitializeTable( int TableSize );
void DestroyTable( HashTable H );
Position Find( ElementType Key, HashTable H );
void Insert( ElementType Key, HashTable H );
ElementType Retrieve( Position P, HashTable H );
HashTable Rehash( HashTable H );
/* Routines such as Delete and MakeEmpty are omitted */
#endif /* _HashQuad_H */

文件名:hashquad.c

  1. #include "hashquad.h"   
  2. #include "fatal.h"   
  3.   
  4. #define MinTableSize (10)   
  5.   
  6. enum KindOfEntry { Legitimate, Empty, Deleted };  
  7.   
  8. struct HashEntry  
  9. {  
  10.     ElementType Element;  
  11.     enum KindOfEntry Info;  
  12. };  
  13.   
  14. typedef struct HashEntry Cell;  
  15.   
  16. /* Cell *TheCells will be an array of */  
  17. /* HashEntry cells, allocated later */  
  18. struct HashTbl  
  19. {  
  20.     int TableSize;  
  21.     Cell *TheCells;  
  22. };  
  23.   
  24. /* Return next prime; assume N >= 10 */  
  25.   
  26. static int  
  27. NextPrime( int N )  
  28. {  
  29.     int i;  
  30.   
  31.     if( N % 2 == 0 )  
  32.         N++;  
  33.     for( ; ; N += 2 )  
  34.     {  
  35.         for( i = 3; i * i <= N; i += 2 )  
  36.             if( N % i == 0 )  
  37.                 goto ContOuter;  /* Sorry about this! */  
  38.         return N;  
  39. ContOuter: ;  
  40.     }  
  41. }  
  42.   
  43. /* Hash function for ints */  
  44. Index  
  45. Hash( ElementType Key, int TableSize )  
  46. {  
  47.     return Key % TableSize;  
  48. }  
  49.   
  50. HashTable  
  51. InitializeTable( int TableSize )  
  52. {  
  53.     HashTable H;  
  54.     int i;  
  55.   
  56.     if ( TableSize < MinTableSize )  
  57.     {  
  58.         Error( "Table size too small!" );  
  59.         return NULL;  
  60.     }  
  61.   
  62.     /* Allocate table */  
  63.     H = malloc( sizeofstruct HashTbl ) );  
  64.     if ( H == NULL )  
  65.         FatalError( "Out of space!!!" );  
  66.   
  67.     H->TableSize = NextPrime( TableSize );  
  68.   
  69.     /* Allocate array of Cells */  
  70.     H->TheCells = malloc( sizeof( Cell ) * H->TableSize );  
  71.     if ( H->TheCells == NULL )  
  72.         FatalError( "Out of space!!!" );  
  73.   
  74.     for ( i = 0; i < H->TableSize; i++ )  
  75.         H->TheCells[ i ].Info = Empty;  
  76.       
  77.     return H;  
  78. }  
  79.   
  80. Position  
  81. Find( ElementType Key, HashTable H )  
  82. {  
  83.     Position CurrentPos;  
  84.     int CollisionNum;  
  85.   
  86.     CollisionNum = 0;  
  87.     CurrentPos = Hash( Key, H->TableSize );  
  88.     while ( H->TheCells[ CurrentPos ].Info != Empty &&  
  89.         H->TheCells[ CurrentPos ].Element != Key )  
  90.         /* Probably need strcpy! */  
  91.     {  
  92.         CurrentPos += 2 * ++CollisionNum - 1;  
  93.         if ( CurrentPos >= H->TableSize )  
  94.             CurrentPos -= H->TableSize;  
  95.     }  
  96.     return CurrentPos;  
  97. }  
  98.   
  99. void  
  100. Insert( ElementType Key, HashTable H )  
  101. {  
  102.     Position Pos;  
  103.   
  104.     Pos = Find( Key, H );  
  105.     if ( H->TheCells[ Pos ].Info != Legitimate )  
  106.     {  
  107.         /* Ok to insert here */  
  108.         H->TheCells[ Pos ].Info = Legitimate;  
  109.         H->TheCells[ Pos ].Element = Key; /* Probably need strcpy! */  
  110.     }  
  111. }  
  112.   
  113. HashTable  
  114. Rehash( HashTable H )  
  115. {  
  116.     int i, OldSize;  
  117.     Cell *OldCells;  
  118.   
  119.     OldCells = H->TheCells;  
  120.     OldSize = H->TableSize;  
  121.   
  122.     /* Get a new, empty table */  
  123.     H = InitializeTable( 2 * OldSize );  
  124.       
  125.     /* Scan through old table, reinserting into new */  
  126.     for( i = 0; i < OldSize; i++ )  
  127.         if ( OldCells[ i ].Info == Legitimate )  
  128.             Insert( OldCells[ i ].Element, H );  
  129.   
  130.     free( OldCells );  
  131.   
  132.     return H;  
  133. }  
  134.   
  135. ElementType  
  136. Retrieve( Position P, HashTable H )  
  137. {  
  138.     return H->TheCells[ P ].Element;  
  139. }  
  140.   
  141. void  
  142. DestroyTable( HashTable H )  
  143. {  
  144.     free( H->TheCells );  
  145.     free( H );  
  146. }  
#include "hashquad.h"
#include "fatal.h"

#define MinTableSize (10)

enum KindOfEntry { Legitimate, Empty, Deleted };

struct HashEntry
{
	ElementType Element;
	enum KindOfEntry Info;
};

typedef struct HashEntry Cell;

/* Cell *TheCells will be an array of */
/* HashEntry cells, allocated later */
struct HashTbl
{
	int TableSize;
	Cell *TheCells;
};

/* Return next prime; assume N >= 10 */

static int
NextPrime( int N )
{
	int i;

	if( N % 2 == 0 )
		N++;
	for( ; ; N += 2 )
	{
		for( i = 3; i * i <= N; i += 2 )
			if( N % i == 0 )
				goto ContOuter;  /* Sorry about this! */
		return N;
ContOuter: ;
	}
}

/* Hash function for ints */
Index
Hash( ElementType Key, int TableSize )
{
	return Key % TableSize;
}

HashTable
InitializeTable( int TableSize )
{
	HashTable H;
	int i;

	if ( TableSize < MinTableSize )
	{
		Error( "Table size too small!" );
		return NULL;
	}

	/* Allocate table */
	H = malloc( sizeof( struct HashTbl ) );
	if ( H == NULL )
		FatalError( "Out of space!!!" );

	H->TableSize = NextPrime( TableSize );

	/* Allocate array of Cells */
	H->TheCells = malloc( sizeof( Cell ) * H->TableSize );
	if ( H->TheCells == NULL )
		FatalError( "Out of space!!!" );

	for ( i = 0; i < H->TableSize; i++ )
		H->TheCells[ i ].Info = Empty;
	
	return H;
}

Position
Find( ElementType Key, HashTable H )
{
	Position CurrentPos;
	int CollisionNum;

	CollisionNum = 0;
	CurrentPos = Hash( Key, H->TableSize );
	while ( H->TheCells[ CurrentPos ].Info != Empty &&
		H->TheCells[ CurrentPos ].Element != Key )
		/* Probably need strcpy! */
	{
		CurrentPos += 2 * ++CollisionNum - 1;
		if ( CurrentPos >= H->TableSize )
			CurrentPos -= H->TableSize;
	}
	return CurrentPos;
}

void
Insert( ElementType Key, HashTable H )
{
	Position Pos;

	Pos = Find( Key, H );
	if ( H->TheCells[ Pos ].Info != Legitimate )
	{
		/* Ok to insert here */
		H->TheCells[ Pos ].Info = Legitimate;
		H->TheCells[ Pos ].Element = Key; /* Probably need strcpy! */
	}
}

HashTable
Rehash( HashTable H )
{
	int i, OldSize;
	Cell *OldCells;

	OldCells = H->TheCells;
	OldSize = H->TableSize;

	/* Get a new, empty table */
	H = InitializeTable( 2 * OldSize );
	
	/* Scan through old table, reinserting into new */
	for( i = 0; i < OldSize; i++ )
		if ( OldCells[ i ].Info == Legitimate )
			Insert( OldCells[ i ].Element, H );

	free( OldCells );

	return H;
}

ElementType
Retrieve( Position P, HashTable H )
{
	return H->TheCells[ P ].Element;
}

void
DestroyTable( HashTable H )
{
	free( H->TheCells );
	free( H );
}

文件名:main.c

  1. #include "hashquad.h"   
  2. #include <stdio.h>   
  3.   
  4. int main()  
  5. {  
  6.     HashTable H = InitializeTable( 10 );  
  7.     int i;  
  8.     printf( "Hash Table: \n" );  
  9.     for ( i = 1; i < 11; i++ )  
  10.     {  
  11.         Insert( i * i, H );  
  12.         printf( "%d:%d\n", i*i, Hash( i * i, 10 ) );  
  13.     }  
  14.     return 0;  
  15. }  
#include "hashquad.h"
#include <stdio.h>

int main()
{
	HashTable H = InitializeTable( 10 );
	int i;
	printf( "Hash Table: \n" );
	for ( i = 1; i < 11; i++ )
	{
		Insert( i * i, H );
		printf( "%d:%d\n", i*i, Hash( i * i, 10 ) );
	}
	return 0;
}



附录:上述代码中用到了Error、FatalError等函数,其实现如下(即fatal.h文件):
  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3.   
  4. #define Error( Str )        FatalError( Str )   
  5. #define FatalError( Str )   fprintf( stderr, "%s\n", Str ), exit( 1 )  
#include <stdio.h>
#include <stdlib.h>

#define Error( Str )        FatalError( Str )
#define FatalError( Str )   fprintf( stderr, "%s\n", Str ), exit( 1 )

备注:本文摘自《数据结构与算法分析 C语言描述 Mark Allen Weiss著》,代码经gcc编译测试通过。

附件下载:http://download.csdn.net/detail/shuxiao9058/4212416#hashsep_20120406.tar.gz ,http://download.csdn.net/detail/shuxiao9058/4212417# hashquad_20120406.tar.gz

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值