/**/ /*************************** *文件名:hash.cpp *功能:散列表 *创建日期:2007-9-27***************************/ #include < iostream > using namespace std; const int m = 11 ; int h( int k, int i) ... { return (k % m + i) % m;} int Insert_hash( int ar[], int k) ... { int i, j; i = 0; while( i < m ) ...{ j = h(k, i); if(ar[j] == -1) ...{ ar[j] = k; return j; } else ++i; } return -1;} void print( int a[], int n) ... { int *b = a + n; // b = a + 4 * n; 因为一个int占四个字节长度 cout << *a << ' '; while( ++a != b ) cout << *a << ' ';} // 初始化函数,将数组 a中元素初始化为v, n 为数组大小 void Init( int a[], int n, int v) ... { int *b = a + n; *a = v; while( ++a != b ) *a = v;} int main() ... { int s[] = ...{ 10, 22, 31, 4, 15, 28, 17, 88, 59 }; cout << "s : "; print( s, sizeof(s) / sizeof(s[0]) ); cout << endl; int hashtable[m]; Init(hashtable, sizeof(hashtable) / sizeof(hashtable[0]), -1); for(int i = 0; i < sizeof(s) / sizeof(s[0]); i++) Insert_hash(hashtable, s[i]); cout << "hashtable : "; print( hashtable, sizeof(hashtable) / sizeof(hashtable[0]) ); cout << endl; return 0;}