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

来源:互联网 发布:人工智能程序发展 编辑:程序博客网 时间:2024/04/30 01:58

一、概述

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

二、实现

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

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

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

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

1. 分离链接法

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


图1 分离链接散列表

文件名:hashsep.h

[cpp] view plaincopyprint?
  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 */  

文件名:hashsep.c
[cpp] view plaincopyprint?
  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. }  

文件名:main.c
[cpp] view plaincopyprint?
  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. }  



2. 开放定址法

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

文件名:hashquad.h

[cpp] view plaincopyprint?
  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 */  

文件名:hashquad.c
[cpp] view plaincopyprint?
  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. }  

文件名:main.c
[cpp] view plaincopyprint?
  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. }  



附录:上述代码中用到了Error、FatalError等函数,其实现如下(即fatal.h文件):
[cpp] view plaincopyprint?
  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 )
0 0